我有如下代码。我制作了名为“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/