简体   繁体   English

用Javascript循环,关闭和addEventListener

[英]Loop, closure and addEventListener in Javascript

I'm sorry for that not so specific title because my English is not good enough to describe this situation clearly in the title. 抱歉,标题不够明确,因为我的英语不够好,无法在标题中清楚地描述这种情况。

I have a code like this: 我有这样的代码:

var e = document.getElementsByClassName( "test" );
var myFunc = function( e ) { 
  e = e + 1; 
};

for ( var i = 0, l = e.length; i < l; i++ ) {
    var t = e[ i ];
    var j = 0;
    (function( n, num ){
        num = 0;
        n.addEventListener("click", function() {
          myFunc( num );
          console.log( num )
        });
    }( t, j ));
}

My intention is to make variable j 's value to increase but the result I still get j=0 after everytime .test is clicked. 我的目的是使变量j的值增加,但是每次单击.test后,我仍然得到j=0的结果。

Demo 演示版

Your problem is that JavaScript does not pass primitive values (like numbers) by reference, but by value. 您的问题是JavaScript不会按引用传递原始值(如数字),而是按值传递。 The myFunc function must return something, you cannot assign to its arguments to change "outside" values. myFunc函数必须返回某些内容,您不能将其分配给其参数以更改“外部”值。

Here's a more modern approach, based on the reasonable assumption that browsers that support getElementsByClassName() also support Array.prototype.forEach() . 这是一种更现代的方法,基于合理的假设,即支持getElementsByClassName()浏览器也支持Array.prototype.forEach()

The following creates one closure with num per HTML element. 以下创建一个闭包,每个HTML元素使用num

 var elems = document.getElementsByClassName("test"), myFunc = function(e) { return e += 1; }; [].slice.call(elems).forEach(function (elem) { var num = 0; elem.addEventListener("click", function () { num = myFunc(num); this.textContent = this.textContent.replace(/\\d*$/, num); }); }); 
 <button class="test">Test 0</button> <button class="test">Test 0</button> <button class="test">Test 0</button> 


Javascript does pass objects by reference, so with a slight change this would work: Javascript 确实通过引用传递对象,因此只需稍作更改即可:

 var elems = document.getElementsByClassName("test"), myFunc = function(properties) { properties.num += 1; }; [].slice.call(elems).forEach(function (elem) { var properties = { num: 0 }; elem.addEventListener("click", function () { myFunc(properties); this.textContent = this.textContent.replace(/\\d*$/, properties.num); }); }); 
 <button class="test">Test 0</button> <button class="test">Test 0</button> <button class="test">Test 0</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM