我有一个元素,我希望每5秒“点击”一次,做某事,然后在5秒后再次点击,做某事,等等”。
所以我使用了setTimeout,它可以完成5秒钟的工作: (在此处找到了示例:How to hide a div after some time period?)
我在这里找到了jQuery事件.trigger:JQuery automatic click after 4 sec
我尝试使用'for'循环它,然后我在前5秒后发生了一个.click事件,然后一次又一次地使用.click事件而没有暂停5秒:http://jsfiddle.net/WTJgt/417/
总的来说,我构建了我的第一个jQuery旋转器:)!
使用右键和左键 - 我希望它在x秒后通过单击“无需单击”来移动幻灯片。
这是我的“下一个”元素按钮的.click事件代码:
// variables
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
$(".r-arrow").click(function(){
moveInPixles = ( rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
}
});
答案 0 :(得分:2)
不要点击,但只需每五秒触发一次javascript函数。通过触发单击,您还可以激活监听事件的所有其他函数,其中一些函数可能与您的代码冲突或被其他库使用。
您可以使用setInterval()来执行此操作。
您的代码应如下所示:
setInterval
将var intervalID = window.setInterval(code, delay);
分配给变量非常重要,然后您就可以使用clearInterval()
window.clearInterval(intervalID)
然后当你需要阻止它时:
{{1}}
答案 1 :(得分:1)
会做的伎俩
var rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
在click
事件中添加
$(".r-arrow").click(function(){
window.clearInterval(rightArrowIntervalId);
// will destroy existing interval
moveInPixles = ( rotCounter + 1) * 746 * -1;
.....
// will create new interval in 5 seconds
rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
});
答案 2 :(得分:1)
setInterval(function () {
$(".r-arrow").click();
}, 5000);
修改强>:
使用setInterval
和clearInterval
,以便您可以在点击按钮时重置间隔。您的代码需要重构,因为您无法按原样使用它。
var intervalId;
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
autoRotate();
function autoRotate() {
intervalId = window.setInterval(function () {
rotateStuff();
}, 5000);
}
function rotateStuff() {
moveInPixles = (rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
}
}
$('.r-arrow').on('click', function () {
window.clearInterval(intervalId);
rotateStuff();
autoRotate();
});
答案 3 :(得分:0)
使用 setInterval 功能代替setimeout
$( function() {
$('#login').click(function() {
alert('login button clicked');
});
setInterval(function() {
$('#login').trigger('click');
}, 500);
});
检查更新的JSFIDDLE
答案 4 :(得分:0)
我不完全理解这个问题,但如果你想每5秒调用一次函数而不是只调用一次,那么就使用setInterval()。