Assign class through JQuery by selecting random ID

2019-08-15 18:19发布

I have a range of divs, each with an incremental ID:

<div id="1">contents</div>
<div id="2">contents</div>
<div id="3">contents</div>
<div id="4">contents</div>
<div id="5">contents</div>
<div id="6">contents</div>

...

I'm trying to assign a class through JQuery by selecting by ID: $('#id').addClass('someClass'); but I want the '#id' to be selected randomly from the range I have there. The range could be sizable, maybe up to 50 ids or more. I'm guessing this will have to read the IDs as number, right? How do I get a random number there?

...Here's the full scheme:

setInterval ( "flipit()", 3000 );

function flipit ( ) {
    $(document).ready(function(){
        var elmId = 'nS_' + (Math.floor(Math.random() * 6) + 1);
        $('#' + elmId).addClass('numSen2');
    });
}
<style type="text/css">

.numSen {
    visibility: hidden;
}
.numSen2 {
    visibility: visible;
}

</style>

<div class="numSen" id="nS_1">contents</div>
<div class="numSen" id="nS_2">contents</div>
<div class="numSen" id="nS_3">contents</div>
<div class="numSen" id="nS_4">contents</div>
<div class="numSen" id="nS_5">contents</div>
<div class="numSen" id="nS_6">contents</div>

标签: jquery
4条回答
SAY GOODBYE
2楼-- · 2019-08-15 19:06

Use Math.floor in combination with Math.random() to create a random selector:

var selector = '#' + (Math.floor(Math.random() * 50) + 1);

$(selector).html();
查看更多
We Are One
3楼-- · 2019-08-15 19:11

I would re-work your elements so they have some class ahead of time. This way, you can select an element from those that you want to change, rather than everything.

<div class="addClasstoMe">contents</div>
<div class="addClasstoMe">contents</div>
<div class="addClasstoMe">contents</div>
<div class="addClasstoMe">contents</div>
<div class="addClasstoMe">contents</div>
<div class="addClasstoMe">contents</div>

And then in your JavaScript:

var elements = $('.addClassToMe');
$(elements[Math.floor(Math.random()*elements.length)]).addClass('someClass');

Untested, but should work, or be close to it.

查看更多
做自己的国王
4楼-- · 2019-08-15 19:18

You can do it even shorter. This will select a div with random id between 1-100 and hide() it:

$('div#'+~~(Math.random()*101)).hide();

Edit:

var $divs = $('div'), len = $divs.length;
$divs.filter('#'+~~(Math.random()*++len)).hide();
查看更多
Bombasti
5楼-- · 2019-08-15 19:25

'#id' is just a string. So, after fixing your IDs (they must start with a letter), build a string like you would anywhere else:

var elmId = 'somePrefix_' + (Math.floor(Math.random() * 5) + 1);
$('#' + elmId).addClass('someClass');
查看更多
登录 后发表回答