我正在做一个编码练习,我已经完成了它并尝试了一下。
这是我的 html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Test</h1>
<script src="jquery.js"></script>
<script src="test.js"></script>
<script>
function runAfter() {
alert("HI!");
var p = document.createElement("p");
p.id = "msg";
p.innerHTML = "TEST!";
document.body.innerHTML += "<br />";
document.body.appendChild(p);
console.log(p.innerHTML);
};
//window.onload=runAfter;
</script>
</body>
</html>
还有 js 文件:
"use strict";
var Widget = {
init: function Widget(width, height) {
this.width = width || 50;
this.height = height || 50;
this.$elem = null;
},
render: function ($where) {
if (this.$elem) {
this.$elem.css({
width: this.width + "px",
height: this.height + "px"
}).appendTo($where);
}
}
};
var Button = Object.create(Widget);
Button.config = function config(width, height, label) {
this.init(width, height);
this.label = label || "ClickMe";
this.$elem = $("<button>").text(this.label);
};
Button.build = function ($where) {
this.render($where);
this.$elem.click(this.onClick.bind(this));
};
Button.onClick = function (evt) {
console.log("Button '" + this.label + "' clicked!");
this.updateMessage("Button '" + this.label + "' clicked!");
};
Button.updateMessage = function (msg) {
var p = document.getElementById("msg");
p.innerHTML = msg;
};
function run() {
let $body = $(document.body);
//create
let btn1 = Object.create(Button);
let btn2 = Object.create(Button);
//initialize
btn1.config(125, 30, "Hello");
btn2.config(150, 40, "World");
//build
btn1.build($body);
btn2.build($body);
};
$(document).ready(run);
如果你离开//window.onload=runAfter;
与 html 中一样,您可以在来自 Button.onClick 函数的控制台中看到问题。但 console.log 可以正常工作
"Button '" + this.label + "' clicked!"
但是如果取消注释,该函数将不起作用。
出了什么问题?动态 this 绑定(bind)是否超出范围到其他地方?
runAfter()
将元素附加到从 test.js 动态生成的 html 页面。
应该发生的是,这两个按钮应该按预期工作 console.log
和<p>
与 id=msg
的段落打印出来与 console.log
相同
最佳答案
如果你注释掉它就会起作用
document.body.innerHTML += "<br/>";
并将其替换为
document.body.appendChild(document.createElement("br"));
编辑并解释:
发生的情况是,当您使用 document.body.innerHTML += 时,您会将innerHTML 作为字符串,添加到该字符串,然后用新字符串替换整个innerHTML。因此,您不是添加已有的内容(就像appendChild() 所做的那样),而是删除所有内容并替换它。
当您删除按钮时,附加到它们的单击处理程序就会消失。并且在替换 insideHTML 后,脚本不会再次运行,因此单击处理程序永远不会重新附加。
关于javascript - 按钮中 onClick 绑定(bind)的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322876/