Javascript多动态addEventListener创建在循环传递参数中不起作用 [英] Javascript multiple dynamic addEventListener created in for loop - passing parameters not working

查看:294
本文介绍了Javascript多动态addEventListener创建在循环传递参数中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用事件侦听器来防止在具有onclick功能的div中的div上发生事件冒泡。这个工作,传递参数我的意图:

I want to use event listeners to prevent event bubbling on a div inside a div with onclick functions. This works, passing parameters how I intended:

<div onclick="doMouseClick(0, 'Dog', 'Cat');" id="button_id_0"></div>
<div onclick="doMouseClick(1, 'Dog', 'Cat');" id="button_id_1"></div>
<div onclick="doMouseClick(2, 'Dog', 'Cat');" id="button_id_2"></div>

<script>
function doMouseClick(peram1, peram2, peram3){
    alert("doMouseClick() called AND peram1 = "+peram1+" AND peram2 = "+peram2+" AND peram3 = "+peram3);
}
</script>

但是,我尝试在循环中创建多个事件侦听器:

However, I tried to create multiple event listeners in a loop with this:

<div id="button_id_0"></div>
<div id="button_id_1"></div>
<div id="button_id_2"></div>

<script>
function doMouseClick(peram1, peram2, peram3){
    alert("doMouseClick() called AND peram1 = "+peram1+" AND peram2 = "+peram2+" AND peram3 = "+peram3);
}

var names = ['button_id_0', 'button_id_1', 'button_id_2'];

    for (var i=0; i<names.length; i++){

        document.getElementById(names[i]).addEventListener("click", function(){
        doMouseClick(i, "Dog", "Cat");

    },false);

}

</script>

它正确地将点击功能分配给每个div,但是每个div的第一个参数 peram1 ,是 3 。我期待3个不同的事件处理程序都通过 i 的不同值 peram1

It correctly assigns the click function to each div, but the first parameter for each, peram1, is 3. I was expecting 3 different event handlers all passing different values of i for peram1.

为什么会发生这种情况?事件处理程序不是全部分开?

Why is this happening? Are the event handlers not all separate?

推荐答案

问题是闭包,因为JS没有块范围(仅功能范围) 我不是你的想法,因为事件功能创建另一个范围,所以当你使用它已经是最新的循环中的的值。您需要保持 i的价值

Problem is closures, since JS doesn't have block scope (only function scope) i is not what you think because the event function creates another scope so by the time you use i it's already the latest value from the for loop. You need to keep the value of i.

使用IIFE:

for (var i=0; i<names.length; i++) {
  (function(i) {
    // use i here
  }(i));
}

使用 forEach

names.forEach(function( v,i ) {
  // i can be used anywhere in this scope
});

这篇关于Javascript多动态addEventListener创建在循环传递参数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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