让getelementsbyclassname正常工作

时间:2014-10-21 08:24:36

标签: javascript

我在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问题,实现看起来很相似。我错过了什么?

1 个答案:

答案 0 :(得分:0)

试试这个: - http://jsfiddle.net/adiioo7/epp4cLpe/2/

<强> 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>