javascript - 如何为对象添加事件监听器?

标签 javascript jquery html css

在为该对象编写成员函数时,我遇到了如何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/

相关文章:

javascript - JS中的小数点位数

javascript - 如何在不使用 html 属性标记数据绑定(bind)值的情况下使用 Knockout 进行绑定(bind)?

jquery - CSS 滑动边框

javascript - 向下滚动时刷新新闻源,浏览器

javascript - Tempdata 未显示在 View ASP.NET C# 中的图像 src 中

jquery - 下拉行 Jquery 菜单

javascript - 当我已经在不同的 iframe 中时,如何从外部 iframe 获取特定的 div

javascript - 检查 div 是否已包含特定元素

javascript - 将DIV元素属性的绑定(bind)拖动到knockoutjs中的对象属性

javascript - 将随机数插入到背景颜色的内联样式中