addEventListener匿名函数中的Javascript变量范围 [英] Javascript variable scope in addEventListener anonymous function

查看:23
本文介绍了addEventListener匿名函数中的Javascript变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当点击每个 div 时,如果点击了 div 1,它应该提醒1",如果点击 div 2,它应该提醒5".我试图使这段代码尽可能简单,因为这在更大的应用程序中是需要的.

When clicking on each div it should alert '1' if div 1 was clicked on or '5' if div 2 was clicked on. I have tried to make this code as easy to as possible because this is needed in a much larger application.

<html>
<head>
<style type="text/css">
#div1 { background-color: #00ff00; margin: 10px; padding: 10px; }
#div2 { background-color: #0000ff; margin: 10px; padding: 10px; }
</style>
<script type="text/javascript">

function init()
{
  var total = 1;

  var div1 = document.getElementById('div1'),
      div2 = document.getElementById('div2');

  var helper = function(event, id)
  {
      if (event.stopPropagation) event.stopPropagation();
      if (event.preventDefault) event.preventDefault();

      alert('id='+id);
  }

  div1.addEventListener('click', function(event) { helper(event, total); }, false);

  total += 4;

  div2.addEventListener('click', function(event) { helper(event, total); }, false);

}

</script>
</head>

<body onload="init();">

<div id="div1">1</div>
<div id="div2">2</div>

</body>
</html>

感谢您的帮助!:-)

推荐答案

问题是事件监听器和 'total' 都存在于同一个作用域 (init())

The problem is that the event listeners and 'total' both exist in the same scope (init())

事件函数总是会在 init() 范围内引用 total,即使在声明事件函数之后它被改变了

The event functions are always going to reference total within the init() scope, even if it is changed after the event functions are declared

为了解决这个问题,事件函数需要在它们自己的范围内有一个不会改变的总数".您可以使用匿名函数添加另一层作用域

To get around this, the event functions need to have a 'total' in their own scope which will not change. You can add another layer of scope using an anonymous function

例如:

(function (total) {
    div1.addEventListener('click', function(event) { helper(event, total); }, false);
}(total));

total += 4;

(function (total) {
  div2.addEventListener('click', function(event) { helper(event, total); }, false);
}(total));

匿名函数将 init() 的当前total"值作为参数传递.这将另一个total"设置为匿名函数的作用域,因此 init() 的 total 是否发生变化并不重要,因为事件函数将首先引用匿名函数的作用域.

The anonymous functions are passed init()'s current 'total' value as a parameter. This sets another 'total' to the anonymous function's scope, so it does not matter if init()'s total changes or not, because the event function will FIRST reference the anonymous function's scope.

另外,你需要在辅助函数的右大括号后面加一个分号,否则脚本会提示'event'未定义.

Also, you need to place a semicolon after the closing brace of the helper function, otherwise the script will complain that 'event' is undefined.

var helper = function(event, id)
{
  if (event.stopPropagation) event.stopPropagation();
  if (event.preventDefault) event.preventDefault();

  alert('id='+id);
};

这篇关于addEventListener匿名函数中的Javascript变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆