如何为对象添加事件侦听器?

时间:2014-05-04 21:01:56

标签: javascript jquery html css

在为该对象编写成员函数时,我遇到了如何addEventLisener对象的问题。

我有一个名为Grid的类,它有一个成员函数create,可以创建一个HTML div元素。现在我想向div添加一个等待click的事件监听器。这是代码。

请注意,我有一个Grid的另一个成员函数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表示HTML DIV Object块内的addEventListener,但我需要它是Grid Object,以便update功能可以叫做。

如何解决这个问题?或者,只要创建包含它的div,就有另一种方法为对象添加侦听器吗?

1 个答案:

答案 0 :(得分:1)

只需使用在事件处理程序范围之外声明的变量

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);
 };