Javascript 使用无法识别的 addEventListener 函数动态创建 HTML 个元素

Javascript dynamically creating HTML elements with addEventListener functions not recognized

如本例所示,我想创建 HTML 元素并将它们附加到作为对象实例一部分的 onclick 函数,有什么方法可以做到这一点? 单击它时得到:

Uncaught ReferenceError: getObj is not defined

function DataSources() {

  var newCheckbox = document.createElement("input");
  newCheckbox.type = "checkbox";
  newCheckbox.addEventListener("click", function() {
    this.ds_checkbox("test2");
  }, false);

  document.getElementById("multi_select").append(newCheckbox);
  this.addLabel = function() {
    var label = document.createElement('label');
    label.innerHTML = "test";
    label.addEventListener("click", function() {
      this.getObj("test");
    }, false);
    document.getElementById("multi_select").append(label);
  }
  this.getObj = function(key) {
    console.log(key);
  };
  this.ds_checkbox = function(p) {
    console.log(key);
  };
}
var datasources = new DataSources();
datasources.addLabel();
<div id="multi_select">
</div>

您有多种选择来解决您的问题:

  • 在构造函数执行时将 this 存储在变量中以供事件回调进一步使用
  • 使用箭头函数作为事件回调,在声明时保留this
  • 使用Function.prototype.bind()强制this值到class实例

在下面的代码中,我在这一行中使用了第一个选项:

var self = this;

function DataSources() {

  var self = this;
  var newCheckbox = document.createElement("input");
  newCheckbox.type = "checkbox";
  newCheckbox.addEventListener("click", function() {
    self.ds_checkbox("test2");
  }, false);

  document.getElementById("multi_select").append(newCheckbox);
  this.addLabel = function() {
    var label = document.createElement('label');
    label.innerHTML = "test";
    label.addEventListener("click", function() {
      self.getObj("test");
    }, false);
    document.getElementById("multi_select").append(label);
  }
  this.getObj = function(key) {
    console.log(key);
  };
  this.ds_checkbox = function(key) {
    console.log(key);
  };
}
var datasources = new DataSources();
datasources.addLabel();
<div id="multi_select">
</div>

您还可以用箭头函数替换事件回调,如下所示:

function DataSources() {

  var newCheckbox = document.createElement("input");
  newCheckbox.type = "checkbox";
  newCheckbox.addEventListener("click", () => {
    this.ds_checkbox("test2");
  }, false);

  document.getElementById("multi_select").append(newCheckbox);
  this.addLabel = function() {
    var label = document.createElement('label');
    label.innerHTML = "test";
    label.addEventListener("click", () => {
      this.getObj("test");
    }, false);
    document.getElementById("multi_select").append(label);
  }
  this.getObj = function(key) {
    console.log(key);
  };
  this.ds_checkbox = function(key) {
    console.log(key);
  };
}
var datasources = new DataSources();
datasources.addLabel();
<div id="multi_select">
</div>