2

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

这就是我所拥有的:

    $(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

有任何想法吗?

4

2 回答 2

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);
    });  
});
于 2012-10-23T03:55:41.903 回答
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); 
    });
});
于 2012-10-23T04:13:05.910 回答