javascript addEventListener 不添加事件

标签 javascript html class oop events

我有如下代码。我制作了名为“Car”的 Javascript 类,并在构造函数中将事件添加到 html“” 标记。但此事件无法触发。

有人可以帮助我吗?

谢谢, 答:

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>

最佳答案

事件应该是click而不是onclick

要绑定(bind)上下文,请在事件处理函数引用上使用 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>

关于javascript addEventListener 不添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415478/

相关文章:

javascript - 使用自定义响应在谷歌地图上绘制路线

javascript - 如何从我发布的 npm 包中访问图像和声音?

javascript - Typescript 中这两个数组赋值有什么区别?

PHP - 在函数内定义类

php - 从类扩展时出现内存错误

javascript - 仅对某些页面使用 Drupal.behaviors?

html - 将垂直滚动条应用于内容框,而不是正文/视口(viewport)

html - 垂直对齐列表中的链接

javascript - 选择没有 ID 或类(class)名称的子项

actionscript-3 - AS3 从静态方法中获取当前类名