这里是例子
在我的项目中我面临着同样的问题,它是如何使
setInterval
玩点击时间 href
变量?
我的意思是,如果我点击第一个 anchor 5 次,那么我在第一个 setInterval
结束之前点击第二个 anchor 3 次。
控制台日志
中的所有结果将是第二个href
值的8倍,我知道这是正常的......但我需要的是5倍第一个 anchor 和第二个 anchor 3 次有什么想法吗?
注意
出于某种原因href
变量必须是全局变量
var href = null;
$('a').click(function(e) {
e.preventDefault();
href = $(this).attr('href');
var timeLeft = 3000;
var counterInterval = setInterval(function() {
timeLeft -= 20;
if (timeLeft < 0) {
console.log(href);
window.clearInterval(counterInterval);
}
}, 20);
})
<a href="first">first anchor</a>
<a href="second">second anchor</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
最佳答案
将代码更改为:
// You're right, href is a global variable which isn't necessary in the demonstration, you can simply remove it
// var href = null;
$('a').click(function(e) {
e.preventDefault();
// let's declare a local variable, href is local to this event
var href = $(this).attr('href');
// change your block to a self invoking function
// the key is that it accepts a parameter and we pass in the href
(function(v) {
var timeLeft = 3000;
var counterInterval = setInterval(function() {
timeLeft -= 20;
if (timeLeft < 0) {
// now we use the parameter v that was passed in
console.log(v);
window.clearInterval(counterInterval);
}
}, 20);
})(href); // <<<<<< this is where we pass in the local href to the self invoke function
});
关于JavaScript : setInterval with global variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599803/