开发者

show and hide several random divs using jquery

i am developing a jquery application. I have 10 divs with quotes. I am trying to create a function that takes a number and randomly displays that number of quotes from the 10 divs for 10 seconds and hide the divs. Then repeat the process again. I have not been able to do it please help me out. here is my code:

$(document).ready(function(){

    var div_number = 4;
    var used_numbers = new Array();
    var todo = setInterval(showQuotes(),3000);

    function showQuotes(){
        used_numbers.splice(0,used_numbers.length);
        $('.quotes').hide();
        for(var inc = 0; inc<div_number; inc++) {
            var random = get_random_number();
            $('.quotes:eq('+random+')').show();
        }
        $('.quotes').fadeOut(3000); 
    }

    function get_random_number(){
        var number = randomFromTo(0,9);
        if($.inArray(number, used_numbers) != -1) {
            get_random_number();
        }
        else {
            used_numbers.push(number);
            return number;
        }
    }
    function randomFromTo(from, to){
       return Math.floor(Math.ra开发者_开发知识库ndom() * (to - from + 1) + from);
    }
});


Changes I made:

  • hide the .quotes on launch via a stylesheet
  • run showQuotes() once before setInterval(showQuotes,10000), and
  • add a .delay() before fading the quotes out
  • Py's 'return' added to get_random_number

http://jsfiddle.net/cMQdj/1/

the changed JavaScript:

$(document).ready(function () {
    var div_number = 4;
    var used_numbers = new Array();
    showQuotes();
    var todo = setInterval(showQuotes, 10000);

    function showQuotes() {
        used_numbers.splice(0, used_numbers.length);
        $('.quotes').hide();
        for (var inc = 0; inc < div_number; inc++) {
            var random = get_random_number();
            $('.quotes:eq(' + random + ')').show();
        }
        $('.quotes').delay(6000).fadeOut(3000);
    }

    function get_random_number() {
        var number = randomFromTo(0, 9);
        if ($.inArray(number, used_numbers) != -1) {
            return get_random_number(); 
        } else {
            used_numbers.push(number);
            return number;
        }
    }
    function randomFromTo(from, to) {
        return Math.floor(Math.random() * (to - from + 1) + from);
    }
});

and add to your stylesheet:

.quotes {display:none}


I didn't test everything, but i already see one point that might block you, the get_random_number does not always return a number. To do so, it should be

function get_random_number(){
    var number = randomFromTo(0,9);
    if($.inArray(number, used_numbers) != -1)
        {
        return get_random_number();
        }
    else
        {
        used_numbers.push(number);
        return number;
        }
}

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜