在为该对象编写成员函数时,我遇到了如何addEventLisener
到该对象的问题。
我有一个名为 Grid
的类,它有一个成员函数 create
,它创建一个 HTML div
元素。现在我想向那个 div
添加一个事件监听器,它等待 click
。这是代码。
请注意,我有另一个用于网格的成员函数 update
。
Grid.prototype.create = function(index) {
var newnode = document.createElement("div");
newnode.setAttribute("class", "grid");
newnode.setAttribute("id", "grid" + index);
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
document.getElementById("whole").appendChild(newnode);
newnode.addEventListener("click", function() {
if (this.live) {
this.live = false;
} else {
this.live = true;
}
this.update(index);
}, false);
this.update(index);
};
问题是,this
表示 addEventListener
block 内的 HTML DIV 对象
,但我需要它是一个 Grid Object
以便可以调用 update
函数。
如何解决这个问题? 或者是否有另一种方法可以在创建包含对象的 div
时为对象添加监听器?
最佳答案
只需使用在事件处理程序范围之外声明的变量
Grid.prototype.create = function(index) {
var grid = this,
newnode = document.createElement("div");
newnode.className = "grid";
newnode.id = "grid" + index;
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
newnode.addEventListener("click", function() {
grid.live = !grid.live;
grid.update(index);
}, false);
document.getElementById("whole").appendChild(newnode);
this.update(index);
};
关于javascript - 如何为对象添加事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23461520/