javascript:带有全局变量

时间:2016-01-04 21:03:54

标签: javascript jquery html

此处为示例打击

在我的项目中,我面临同样的问题,而且是如何制作的 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;
&#13;
&#13;

1 个答案:

答案 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
});