问题
Instead of triggering code on click of the element, I want this function to run automatically after 4 seconds. How can I make it possible?
$('a.close,form #okLogin, mask').live('click',function () {
$('.login-popup').fadeOut(300);
$('#mask').remove();
return false;
});
回答1:
$(function(){
setTimeout(function(){
$('.login-popup').fadeOut(300);
$('#mask').remove();
},4000);
});
回答2:
setTimeout(function () {
$('.login-popup').fadeOut(300);
$('#mask').remove();
}, 4000);
回答3:
Use the built in setTimeout()
function in JavaScript. For executing a function after a period of time, there is no need to use jQuery:
setTimeout(function () {
// your function goes here
$('.login-popup').fadeOut(300);
$('#mask').remove();
}, 4000); // this number is in milliseconds
References:
- How JavaScript Timers Work - John Resig weblog
- window.setTimeout - MDN
回答4:
use setTimeout()
setTimeout(function(){
$('.login-popup').fadeOut(300);
$('#mask').remove();
},4000);
回答5:
setTimeout(function(){
$('#okLogin').click();
}, 4000);
IMPORTANT live()
method is deprecated. use .on()
回答6:
Try this:
$('a.close,form #okLogin, mask').on('click', function () {
$('.login-popup').fadeOut(300);
$('#mask').remove();
return false;
});
$(window).load(function () {
setTimeout(function () {
$('#okLogin').triggerHandler('click')
}, 4000);
});
来源:https://stackoverflow.com/questions/16813672/execute-a-function-after-x-seconds-in-jquery