【问题标题】:javascript addEventListener don't add eventjavascript addEventListener 不添加事件
【发布时间】:2016-01-29 16:02:26
【问题描述】:

我有如下代码。我制作了名为“Car”的Javascript类,并在构造函数中将事件添加到html“”标签。但是这个事件不能触发。

有人可以帮我吗?

谢谢, A.

function Car(model, brand) {

  this.model = model;
  this.brand = brand;

  document.getElementById('button').addEventListener('onclick', this.info);
}

// method
Car.prototype.info = function() {
  alert("It is " + this.model);
};

// define cariable
var car = new Car("RX7", "Mazda");

// Invoke method in html
//car.info();

// second way
window.onload = function() {
  var car = new Car("RX7", "Mazda");
};
<button id="button">Click me</button>

【问题讨论】:

    标签: javascript html class oop events


    【解决方案1】:

    事件应该是click 而不是onclick

    要绑定上下文,请在事件处理函数引用上使用bind(this)

    function Car(model, brand) {
      this.model = model;
      this.brand = brand;
    
      document.getElementById('button').addEventListener('click', this.info.bind(this));
      //                                                 ^^^^^^^            ^^^^^^^^^^
    }
    
    // method
    Car.prototype.info = function() {
      alert("It is " + this.model);
    };
    
    // define cariable
    var car = new Car("RX7", "Mazda");
    
    // Invoke method in html
    //car.info();
    
    // second way
    window.onload = function() {
      var car = new Car("RX7", "Mazda");
    };
    <button id="button">Click me</button>

    我希望这只是为了演示目的,如果您想在实际项目中使用它,请使用以下代码。

    function Car(model, brand) {
      this.model = model;
      this.brand = brand;
    }
    
    // method
    Car.prototype.info = function() {
      alert("It is " + this.model);
    };
    
    // define cariable
    var car = new Car("RX7", "Mazda");
    
    document.addEventListener('DOMContentLoaded', function() {
      var car = new Car("RX7", "Mazda");
      document.getElementById('button').addEventListener('click', car.info.bind(car));
    });
    <button id="button">Click</button>

    【讨论】:

    • 非常感谢:-) 很好的答案。我想把它作为“通用”搜索过滤器来做,它不需要太多需要添加代码的地方。这就是我在构造函数中添加事件的原因。在您的第一个示例中,方法在一次 clisk 后调用 2 次。可能是什么原因?第二个示例运行良好。
    • @arrowman 在第一个示例中,Car 构造函数被调用了两次,因此事件在同一个元素上被绑定了两次,导致处理程序在单击时运行两次。我建议使用第二个示例。
    【解决方案2】:

    @Tushar 非常感谢您。如果没有你的帮助,我不会这样做 :-)

    对于希望将所有内容“更多地”放在一个类中的人,我在@Tushar 代码中准备了一些更改。

    但我不知道它是否在任何编程标准中都是一致的。

    function Car(model, brand) {
      this.model = model;
      this.brand = brand;
      
      document.getElementById('button').addEventListener('click', this.info.bind(this));
    }
    
    // method
    Car.prototype.info = function() {
      alert("It is " + this.model);
    };
    
    
    document.addEventListener('DOMContentLoaded', function() {
      var car = new Car("RX7", "Mazda");
    });
    <button id="button">Click</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多