使用jQuery模拟下一个按钮单击

时间:2012-01-09 19:47:43

标签: javascript jquery

不确定这是否可行,但我的网站上有一个幻灯片显示,当点击相关幻灯片时,幻灯片会滑入。

我想要做的是添加一个计时器,以便在3秒后点击下一个按钮,使我的幻灯片自动滑动。

$('#button a').click(function(){
    var integer = $(this).attr('rel');
    $('#myslide .cover').animate({left:-720*(parseInt(integer)-1)})  /*----- Width of div mystuff (here 160) ------ */
    $('#button a').each(function(){
    $(this).removeClass('active');
        if($(this).hasClass('button'+integer)){
            $(this).addClass('active')}
    });


});

我添加了一个小提琴...... http://jsfiddle.net/5jVtK/

3 个答案:

答案 0 :(得分:3)

您可以通过

触发jQuery元素的click事件
$('#button a').click();

要以3秒的间隔发生这种情况,请使用setInterval()

function simulateClick(){
    $('#button a').click();
};

setInterval(simulateClick, 3000);

答案 1 :(得分:3)

最简单的方法是使用setTimeout(在延迟后发生一次)或setInterval(经常发生)。

setTimeout( function() { $( '#button a' ).trigger( 'click' ) }, 3000 );

setInterval( function() { $( '#button a' ).trigger( 'click' ) }, 3000 );

一旦实现了这一点,您可能需要考虑其他一些细节,例如当用户的鼠标悬停在下一个按钮或幻灯片放映时停止自动进展(因为这意味着对当前显示的内容感兴趣)和在mouseout上恢复自动执行。

下一步:听起来你需要弄清楚如何动态找到正确的按钮来触发以继续推进多张幻灯片。这是一种方法:

`

function click() {
    // Find the button for the next slide in relationship to the currently active button
    var $next = $( '#button' ).find( '.active' ).next( 'a' );

    // If there isn't one, go to the beginning
    if ( ! $next.length ) {
        $next = $( '#button' ).find( 'a' ).first();
    }

    // Trigger the click
    $next.trigger( 'click' );

    setTimeout(click, 3000);
}

setTimeout(click, 3000);

这是一个小提琴的链接,显示了这一点:

http://jsfiddle.net/5jVtK/1/

答案 2 :(得分:0)

这样的事情应该有效。这样我们以一定间隔运行一个函数,并且单击也会触发相同的函数。计时器永远不需要激活按钮,只需激活按钮也激活的功能。

$(document).ready(function() {
   var timer = setInterval( slideFunction, 5000);

    $('#button a').click(function(){
     slideFunction();
    });
    function slideFunction(){
        var integer = $('#button a').attr('rel');
        $('#myslide .cover').animate({left:-720*(parseInt(integer)-1)})  /*----- Width of div mystuff (here 160) ------ */
        $('#button a').each(function(){
            $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
            $(this).addClass('active')}
        });
    }
});
相关问题