如果未按下按钮,则在30秒内自动执行该功能

时间:2012-09-06 09:31:49

标签: javascript jquery html

我想在网页中添加以下功能:如果用户在30秒内未按下“接受”按钮,则会自动执行$('#popupBoxAccept').click( function() {..}

$(document).ready(function() {
    loadPopupBox();
});

function loadPopupBox() {   // to load the Popupbox 
    $('#popup_box').fadeIn("slow");     
}

$('#popupBoxAccept').click( function() {            
    //...
});

$('#popupBoxDecline').click( function() {           
    //...
});

<div id="popup_box">
    <a id="popupBoxAccept">Accept</a>
    <a id="popupBoxDecline">Decline</a>     
</div>

5 个答案:

答案 0 :(得分:7)

jsFiddle demo

var tim = setTimeout(function(){
    $('#popupBoxAccept').click();
},30000);

手册中,点击:

$('#popupBoxAccept').click(function(){
     clearTimeout(tim);
      // ........
});

正如@Elias所建议的那样:

$('#popupBoxDecline').click( function() {
    clearTimeout(tim);           
    //...
});

答案 1 :(得分:4)

一个简单的选择是使用标志和setTimeout函数:

var clicked = false;
$("#popupBoxAccept").click(function() {
    clicked = true;
    //...
});

setTimeout(function() {
    if (!clicked) {
        $("#popupBoxAccept").click();
    }
}, 30000);

答案 2 :(得分:1)

试试这个

setTimeOut(function(){
  $('#popupBoxAccept').click( function() {            
    //...
});
}, 30000);

答案 3 :(得分:1)

设置超时:

var tim;//global, I'll provide a (more complex) solution that doesn't need them, too
function loadPopupBox() {   // to load the Popupbox 
    $('#popup_box').fadeIn("slow");
    tim = setTimeout(function()
    {
        $('#popup_box').click();
    },30000);
}

$('#popupBoxAccept').click( function() {            
    clearTimeout(tim);
});

现在,不使用 EVIL 全局变量:

$(document).ready(function()
{
    (function(popup,accept,decline)
    {
        popup.fadeIn("slow");
        var tim = setTimeout(function()
        {
            accept.click();//<-- access to reference is preserved
        },30000);
        accept.click(function()
        {
            clearTimeout(tim);
            //do accept stuff
        });
        decline.click(function()
        {
            clearTimeout(tim);//<-- need that here, too!
            //do decline stuff
        });
    })($('#popup_box'),$('#popupBoxAccept'),$('#popupBoxDecline'));
    //pass all 3 elements as argument --> less typing, and is more efficient:
    //the DOM is only searched once for each element
});

为什么这有用?简单:您现在可以在另一个上下文中使用var tim,而不会丢失对超时的引用。闭包,名称说明了一切:所有变量和引用都在同一范围内整齐地捆绑在一起,并且无法访问,但是在声明的范围内:

var foo = (function()
{
    var invisible = 'Now you see me';
    return function()
    {
        return invisible;
    }
};
console.log(invisible);//<-- undefined
var invisible = 'Now you don\'t';
console.log(foo());//<-- Now you see me
console.log(invisible);//Now you don\'t

答案 4 :(得分:0)

尝试将其放入$(document).ready()来电:

setTimeout(function() {
    if(!clicked) {
        $('#popupBoxAccept').click();
    }
}, 30000);

然后改变

$('#popupBoxAccept').click( function() {
    //...
});

var clicked = false;
$('#popupBoxAccept').click( function() {
    clicked = true;
    //...
});