jQuery为随机文本数组添加超时

时间:2012-10-23 03:50:38

标签: jquery timeout

我有一个链接可以在每次点击时更改文本,但我试图找到一种方法让它在一段时间后自动切换到下一个变量,有点像旋转器。

这就是我所拥有的:

    $(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }
    $('#button-reload').click(function() {
            $(this).html(loadQuote(randNumber()));
    });
    $('#button-reload').html(loadQuote(randNumber()));
});​

这是一个jsfiddle

任何想法?

2 个答案:

答案 0 :(得分:3)

尝试使用window.setInterval()代码,如下所示:

$(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }

    var interval = window.setInterval(function(){
        $('#button-reload').html(loadQuote(randNumber()));            
    }, 3000);   

    $('#button-reload').click(function() {
        $(this).html(loadQuote(randNumber()));

        //uncomment line bellow to stop intarval when button clicked.
        //window.clearInterval(interval);
    });  
});

答案 1 :(得分:2)

$(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    var $theLink = $('#button-reload');

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }

    function changeTheQuote() {
        $theLink.html(loadQuote(randNumber())); 
    }

    var interval = window.setInterval(function(){
        changeTheQuote();
    }, 3000); 

    $theLink.click(function() {
        window.clearInterval(interval);
        changeTheQuote();
        interval = window.setInterval(function(){
            changeTheQuote();
        }, 3000); 
    });
});