此处为示例打击
在我的项目中,我面临同样的问题,而且是如何制作的
setInterval
玩点击时间href
变量?
我的意思是如果我点击第一个锚5次然后我在第一个setInterval
结束之前点击第二个锚3次。
console log
中的所有结果将是第二href
值的8倍,这是正常的我知道...但我需要的是第一个锚5次,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);
})
&#13;
<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>
&#13;
答案 0 :(得分:1)
将您的代码更改为:
// 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
});