0

在我的测试中,该mylog函数被调用了 3 次,但查看源代码我想它应该只执行两次。

<html>
<div id='log'></div>
<script>

var Foo = { counter : "inside the Foo object" };
var counter = "Global";

Foo.method = function() {
    var counter = "inside Foo.method";
    mylog("counter = "+this.counter);
    function test() {
        // this is set to the global object
        mylog("counter = "+this.counter);
    }
    test();
}

Foo.method();

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML += log.innerHTML + msg + "<br />";
}
</script>
</html>

http://jsfiddle.net/8BBF7/

这是输出:

counter = inside the Foo object
counter = inside the Foo object
counter = Global

正如我所说,我预期mylog的函数只被调用了两次。有人可以解释一下为什么会这样吗?

4

4 回答 4

4

只需将其更改+==在线log.innerHTML += log.innerHTML + msg + "<br />";或保留并使用表格log.innerHTML += msg + "<br />";

于 2013-07-12T11:41:24.480 回答
2

那是因为这个

log.innerHTML += log.innerHTML + msg + "<br />";

您还添加了当前的 innerHTML,因此您复制了之前的日志。像这样做

log.innerHTML += msg + "<br />";

或者

log.innerHTML = log.innerHTML + msg + "<br />";
于 2013-07-12T11:43:29.997 回答
2

该函数被调用了 2 次,但是您在附加 log.InnerHTML 时犯了一个错误。你追加 log.innerHTML 2 次

工作代码:

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML +=  msg + "<br />";
}

http://jsfiddle.net/8BBF7/16/

于 2013-07-12T11:46:20.307 回答
1

它只被调用了两次。检查您的mylog()

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML += log.innerHTML + msg + "<br />";
}

要么使用

log.innerHTML = log.innerHTML + msg + "<br />";

或者

log.innerHTML += msg + "<br />";
于 2013-07-12T11:43:08.147 回答