我需要帮助从this.load
内部调用thediv.onclick
函数。我删除了大部分代码,所以它非常基本,但我真的找不到办法。这是我现在拥有的:
function CreatePizza(Name, Toppings) {
this.n = Name;
this.t = Toppings;
this.load = function loadpizza() {
//function that i want to be called
}
this.create = function button() {
var thediv = document.createElement("div");
thediv.onclick = function() {
// Call this.load function here
}
}
}
答案 0 :(得分:6)
问题是在onclick
处理程序中,this
会引用<div>
,而不是您重复引用的其他this
。
两种可能的解决方案:
保存对所需this
的引用:
that = this;
thediv.onclick = function () {
that.load()
};
将this
绑定到您的函数:
thediv.onclick = function () {
this.load();
}.bind(this);
或者,如果这是您在该功能中唯一做的事情:
thediv.onclick = this.load.bind(this);
答案 1 :(得分:2)
由于闭包,您可以简单地将this
分配给变量并从中调用它!
function CreatePizza(Name, Toppings) {
var self = this;
this.n = Name;
this.t = Toppings;
this.load = function loadpizza() {
//function that i want to be called
}
this.create = function button() {
var thediv = document.createElement("div");
thediv.onclick = function() {
self.load();
}
}
}
我想提一下,在任何人开始使用火焰战之前更好的 - 并不一定更好 - 将事件附加到你的div(在我看来更优雅)是使用thediv.addEventListener('click', self.load, false)
。不过只是旁注。
答案 2 :(得分:1)
在绑定事件之前备份this
对象。
this.create = function button() {
var that = this,
thediv = document.createElement("div");
thediv.onclick = function() {
// Call this.load function here
that.load();
}
}
答案 3 :(得分:0)
function CreatePizza(Name, Toppings) {
this.n = Name;
this.t = Toppings;
var foo = function loadpizza() {
//function that i want to be called
};
this.load = foo;
this.create = function button() {
var thediv = document.createElement("div");
thediv.onclick = function() {
foo();
}
}
}
答案 4 :(得分:0)
function CreatePizza(Name, Toppings) {
this.n = Name;
this.t = Toppings;
this.load = function loadpizza() {
//function that i want to be called
}
var self = this;
this.create = function button() {
var thediv = document.createElement("div");
thediv.onclick = function() {
self.load()
}
}
}