我有两个原型函数showPopup
和buildView
。在buildView
中,我正在生成一个带有按钮的动态HTML,并希望在单击按钮时调用showPoup
。但是,单击按钮时,它会抛出
错误:属性“ showPopup”的值为null或未定义,不是 一个功能对象
MyEditor.prototype.buildView = function(id) {
document.getElementById("myView").innerHTML = "<input type='button' value='Edit' onclick='showPopup(getName(id), getPlace(id))' />";
}
MyEditor.prototype.showPopup = function(name, place) { }
我什至尝试使用onclick='MyEditor.showPopup(getName(id), getPlace(id))'
,也没有用。
答案 0 :(得分:3)
document.createElement()
this
上下文#myView
元素#myView
元素MyEditor.prototype.buildView = function(id) {
const btn = document.createElement('input')
btn.type = 'button';
btn.value = 'Edit'
btn.addEventListener('click', () => {
this.showPopup(getName(id), getPlace(id))
}, false)
// empty out #myView
const view = document.getElementById('myView')
while (view.firstChild) {
view.removeChild(view.firstChild)
}
view.appendChild(btn)
}
答案 1 :(得分:2)
因为您必须调用this.showPopup()
,只有在手动构建DOM时,这才可能:
MyEditor.prototype.buildView = function(id) {
const button = document.createElement("input");
button.type = "button";
button.value = "Edit";
button.onclick = (evt) => {
this.showPopup(getName(id), getPlace(id));
};
document.getElementById("myView").appendChild(button);
}
答案 2 :(得分:0)
如果要通过html文本构建元素,则需要执行以下操作。
MyEditor = function() {};
MyEditor.prototype.buildView = function(id) {
document.getElementById("myView").innerHTML = "<input type='button' value='Edit' onclick='editor.showPopup(\"name\", \"id\")' />";
}
MyEditor.prototype.showPopup = function(name, place) {
console.log(name)
}
var editor = new MyEditor()
editor.buildView();
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body>
<div id="myView"></div>
</body>
</html>