简体   繁体   English

JavaScript在所有元素上执行最后一个eventListener

[英]JavaScript executing last eventListener on all elements

I'm currently working on a project which contains 4 canvas elements. 我目前正在一个包含4个canvas元素的项目中。 When a click occurs on an element, it will launch an event which draws the content of the canvas. 在元素上单击时,它将启动一个事件,该事件绘制画布的内容。

function canvasItem(cv, ctx, id){
    this.cv = cv;
    this.ctx = ctx;
    this.id = id;
}

canvasItem.prototype.drawLine = function(){
    console.log("drawing "+this.id);
}

var lineView = {
   canvasItems: [],
    init : function(){
        items = document.getElementsByClassName("highlight");
        if(items){
            for(var i = 0; i<items.length; i++){
                var ctx = items[i].getContext("2d");
                var cv = items[i];
                this.canvasItems.push(new canvasItem(cv, ctx, i));
            }
        }
        this.addListeners();
    },
    addListeners : function(){
        var containers = document.getElementsByClassName("articleContainer");
        for(var i = 0; i<containers.length; i++){
            var currentItem = this.canvasItems[i];
            containers[i].addEventListener("click", currentItem.drawLine, false);
        }
    }
}

window.onload = function(){
    lineView.init();
}

Each canvas element will show the output drawing when it receives a click. 每个画布元素在收到点击后都会显示输出drawing I figured out that it's using the variable i=4 and executing the canvasItems[4].drawLine function. 我发现它正在使用变量i=4并执行canvasItems[4].drawLine函数。

I think this might be because it's passing the variable i by reference in the canvasItems[i].drawLine line. 我认为这可能是因为它在canvasItems[i].drawLine行中通过引用传递了变量i I'm not sure if this is correct, but I hope someone could show me what I'm doing wrong. 我不确定这是否正确,但希望有人能告诉我我做错了什么。

Below is the HTML pattern which occurs four times in the HTML page: 以下是在HTML页面中出现四次的HTML模式:

<div class="articleContainer">
     <article>
          <h3>Title</h3>
          <p>
                text
          </p>
      </article>
      <canvas class="highlight"></canvas>
</div>

It was primarily a closure issue. 这主要是关闭问题。 Below is the fix. 下面是修复程序。

for (var i = 0; i < containers.length; i++) {
            (function (index) {
                var currentItem = lineView.canvasItems[index];
                containers[index].onclick = function (){
                    currentItem.drawLine();
                };
            }) (i);
        }

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

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