Let's say I have some classes like:
<div class="something" style="display: none">Some text I would like to show</div>
<div class="something" style="display: none">Some text2 I would like to show</div>
<div class="something" style="display: none">Some text3 I would like to show</div>
<div class="something" style="display: none">Some text4 I would like to show</div>
<div class="something" style="display: none">Some text5 I would like to show</div>
And I want to show random class every few seconds. I suppose pseudo-code would be something like that:
setInterval(function() {
$('.something').hide();
var rand_number = random(1, ('.something').length);
开发者_开发问答 $('.something').array[rand_number].show();
}, 5000);
Thanks.
Try to avoid evaluating $('.something')
too often:
setInterval(function() {
var $s = $('.something');
var r = Math.floor(Math.random() * $s.length);
$s.hide().eq(r).show();
}, 5000);
If you know that the list of elements won't change once the document is loaded, you can simplify further:
$(function() { // short-hand for document.ready
var $s = $('.something');
var count = $s.length;
setInterval(function() {
var r = Math.floor(Math.random() * count);
$s.hide().eq(r).show();
}, 5000);
});
setInterval(function() {
var $something = $('.something').hide();
var rand_number = Math.floor(Math.random() * $something.length);
$something.eq(rand_number).show();
}, 1000);
Example on jsfiddle
setInterval(function() {
$('.something').hide();
var classes = $('.something');
var rand_number = Math.round(Math.random() * (classes.length));
$(classes[rand_number]).show();
}, 5000);
setInterval(function() {
$('.something').hide();
var rand_number = random(0, ('.something').length - 1);
$('.something:eq('+rand_number+')').show();
}, 5000);
Your example looks pretty solid, however, I have a few suggestions: 1. Your class .something should probably have display: none in the stylesheet and not inline; additionally (initially) you don't have to hide in programmatically. No sense in repeating that over an over again.
This could also be achieved using IDs that are stored in an array, so you don't have to query the DOM on every time to get the elements. You can use this in conjunction with $(".something").hide(); if you don't want to store the previously shown item. This may not be practical if the divs are dynamically generated.
You could use one element and update its content; of course, there may be aesthetic reasons for using different elements that aren't implied in your example.
You could use one element and update its content; of course, there may be aesthetic reasons for using different elements that aren't implied in your example.
精彩评论