简体   繁体   English

如何正确添加addeventlistener?

[英]How to properly add addeventlistener?

I try add to array with image event listener which catch load event and it's works. 我尝试使用捕获负载事件的图像事件监听器添加到数组中,并且有效。 But sometimes i parameter passed to the decrement function is the same for all requests 但是有时我传递给减量函数的参数对于所有请求都是相同的

var imgNumb = vectors.length;
function decrement(i, type){
    imgNumb--;
    console.log('Processed '+ type+' nr: ' + i + '. Left: '+ imgNumb);
}
for(var i in vectors)
{
    if(jQuery('#canvas-'+i).length != 0){
    var tempCont = document.getElementById('canvas-'+i);
    tempImage[i] = new Image();
    alert(i);
    tempImage[i].addEventListener('load', function(){
        decrement(i, 'canvas');
    }, false);
    type[i] = 'canvas';
       tempImage[i].src = tempCont.toDataURL();
    }
}

for example i get: 例如我得到:

Processed canvas nr: 1. Left: 2
Processed canvas nr: 2. Left: 1
Processed canvas nr: 2. Left: 0

but alert (if it isn't inside handler) always return correct key number. 但是警报(如果它不在处理程序内部)始终返回正确的密钥号。

You are creating a function in a loop which is dependent on the loop variable. 您正在循环中创建一个函数,该函数取决于循环变量。 All functions reference the same i . 所有函数都引用相同的 i You have to introduce a new scope (by calling a function) to capture the current value of the variable: 您必须引入一个新的作用域(通过调用一个函数)来捕获变量的当前值:

(function(index) {
    tempImage[index].addEventListener('load', function(){
        decrement(index, 'canvas');
    }, false);
}(i));

Here we use an immediate or self-invoking function . 在这里,我们使用立即自调用函数


Don't use for...in to iterate over arrays . 请勿for...in数组上进行迭代 Use a normal for loop. 使用普通的for循环。

@Felix's answer is correct, but I thought I might show an alternative solution that might be more readable: @Felix的答案是正确的,但我认为我可能会展示一种更具可读性的替代解决方案:

var imgNumb = vectors.length,
    tempImage = [];

function decrement(i, type) {
    imgNumb--;
    console.log('Processed ' + type + ' nr: ' + i + '. Left: ' + imgNumb);
}

$.each(vectors, function(i, element) {
    var $canvas = $('#canvas-' + i);
    if ($canvas.length) {
        tempImage[i] = $('<img/>', {
            src: $canvas.get().toDataURL(),
            load: function() {
                decrement(i, 'canvas');
            }
        });
        type[i] = 'canvas';
    }
});

It's not clear in the question if vectors is a jQuery object or a plain JS array, so I've taken the safe assumption and used $.each() . 这个问题尚不清楚, vectors是jQuery对象还是纯JS数组,因此我采用了安全的假设并使用了$.each() If vectors is a jQuery object, you can use .each() instead. 如果vectors 一个jQuery对象,则可以改用.each()

Other fixes: 其他修复:

  • Don't use for... in to iterate over arrays. 不要for... in遍历数组。
  • Just check the truthiness of jQuery('#canvas-' + i).length 只需检查jQuery('#canvas-' + i).length的真实性jQuery('#canvas-' + i).length
  • You're using jQuery - why use document.getElementById() ? 您正在使用jQuery-为什么要使用document.getElementById()
  • Again, you're using jQuery - why use addEventListener() ? 同样,您使用的是jQuery-为什么要使用addEventListener()

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

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