jQuery 面向对象创建了 dom 元素并添加了事件监听器

jQuery object-oriented created dom element and add event listener

我有个小问题。我在一个对象中创建了一些元素并且工作正常。但是现在我想添加一些 EventListeners 来执行对象内部的函数,问题是我无法执行函数 "setSelection"。 ("this"不是对象的"this",而是点击函数内部事件的"this"。

function Object() {
    this.init = function () {
        // delete table
        // ...
        // set table
        $('tr').append('<td id="1">test</td>');

        $('td').click(function() {
            // execute setSelection
        });
    }

    this.setSelection = function(x) {
        alert('You clicked id ' + x);
    }
}

$(document).ready(function() {
    x = new Object();
    x.init();
});
    $('td').click((function(e) {
        // execute setSelection
        this.setSelection(...);
    }).bind(this));

您可以通过将外部作用域中 this 的引用存储到可以在 click 事件处理程序中使用的变量来解决此问题:

function Object() {
    var _this = this;

    this.init = function () {
        // delete table
        // ...
        // set table
        $('tr').append('<td id="1">test</td>');

        $('td').click(function() {
            _this.doSomething();
        });
    }

    this.setSelection = function(x) {
        alert('You clicked id ' + x);
    }
}

我的做法是:

function Object() {
  this.init = function () {
    // delete table
    // ...
    // set table
    $('tr').append('<td id="1">test</td>');

    $('td').click(function() {
      setSelection(this);
    });
  }

  setSelection = function(x) {
    alert('You clicked id ' + x);
  }
}

我已经解决了问题...

function Object() {
    this.init = function () {
        // delete table
        // ...
        // set table
        $('tr').append('<td id="1">test</td>');

        this.setSelection();
    }

    this.setSelection = function() {
       $('td').click(function() {
            alert('You clicked id ' + $(this).attr('id'));
        });
    }
}

$(document).ready(function() {
    x = new Object();
    x.init();
});