Javascript 如何为对象添加事件侦听器?
在为某个对象编写成员函数时,如何Javascript 如何为对象添加事件侦听器?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,在为某个对象编写成员函数时,如何addEventLisener添加到该对象,我遇到了一些问题 我有一个名为Grid的类,它有一个成员函数create,用于创建HTMLdiv元素。现在我想在div中添加一个事件侦听器,它等待单击。这是代码 请注意,我还有另一个用于网格的成员函数update Grid.prototype.create = function(index) { var newnode = document.createElement("div"); newnode.se
addEventLisener
添加到该对象,我遇到了一些问题
我有一个名为Grid
的类,它有一个成员函数create
,用于创建HTMLdiv
元素。现在我想在div
中添加一个事件侦听器,它等待单击
。这是代码
请注意,我还有另一个用于网格的成员函数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);
};
问题是,此
表示addEventListener
块中的HTML DIV对象
,但我需要它是网格对象
,以便调用更新
函数
如何解决此问题?或者在创建包含对象的
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);
};