Sunday, 5 February 2017

javascript - addEventListener, for(), index. how to use closure?

No, the third argument of addEventListener is the useCapture one. See MDN for more information.


But you can use:


for( var i = 0; i < items.length; i++ ){
(function(i){
items[i].addEventListener('click', function(event) {
alert( i );
}, false);
})(i);
}

or


var handler = function(event) {
var i = items.indexOf(this);
alert( i );
};
for( var i = 0; i < items.length; i++ ){
items[i].addEventListener('click', handler, false);
}

The first one creates a new event handler for each element, so it needs more memory. The second one reuses the same event listener, but uses indexOf, so it's more slow.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...