我需要帮助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
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是在onclick处理程序内部,this将引用<div>,而不是this您重复引用的另一个.
两种可能的解决方
保存对您所需的引用this:
that = this;
thediv.onclick = function () {
that.load()
};
Run Code Online (Sandbox Code Playgroud)绑定this你的功能:
thediv.onclick = function () {
this.load();
}.bind(this);
Run Code Online (Sandbox Code Playgroud)
或者,如果这是你在该功能中唯一做的事情:
thediv.onclick = this.load.bind(this);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
379 次 |
| 最近记录: |