我在HTML页面中有两个带有classname测试的标签。当我尝试执行以下代码并使用getelementsbyclassname显示输出时,最后一个输出显示两次,而不是显示第一个输出,后面显示第二个输出。
var callbackTester = function (callback) {
var tryMe = "Are you ready, ";
callback(tryMe);
};
var createMessageHandler = function (client) {
this.client = client;
this.result = function (foo) {
foo(function (msg) {
var elements = document.getElementsByClassName('test');
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = (msg + " " + this.client);
};
}.bind(this));
}
};
(new createMessageHandler("John")).result(callbackTester);
(new createMessageHandler("Jason")).result(callbackTester);
查看了很多SO问题,实现看起来很相似。我错过了什么?
答案 0 :(得分:0)
<强> JS: - 强>
var callbackTester = function (callback) {
var tryMe = "Are you ready, ";
callback(tryMe);
};
var createMessageHandler = function (client) {
this.client = client;
this.result = function (foo) {
foo(function (msg) {
var el = document.createElement("div");
el.className = "test";
el.innerHTML = (msg + " " + this.client);
document.getElementById("temp").appendChild(el);
}.bind(this));
}
};
(new createMessageHandler("John")).result(callbackTester);
(new createMessageHandler("Jason")).result(callbackTester);
<强> HTML: - 强>
<div id="temp"></div>