哟社区!这里可能需要一些见解..:)我正在学习一些更高级的 js 概念。我正在运行此代码,但结果没有按照我的预期显示......我看不到错误......有什么想法吗?谢谢!
<script type="text/javascript">
(function() {
var results, queue = [];
this.assert = function(pass, msg) {
var type = pass ? "PASS" : "FAIL";
var str = "<li class='" + type + "'><b>" +
type + "</b> " + msg + "</li>";
if ( queue )
queue.push( str );
else
results.innerHTML += str;
};
window.addEventListener("load", function() {
results = document.getElementById("results");
results.innerHTML = queue.join('');
queue = null;
});
// calling assert but it's not showing up the <li> with the message....( why? )
assert( true, "I always pass!" );
})();
</script>
最佳答案
".is there any chance that else-statement will be used? why is the idea of the else-statement?"
这样assert()
函数的工作原理是,如果在文档加载事件发生之前调用它,则任何结果都会存储在 queue
中。数组:条件if (queue)
为真,因为 queue
引用数组。
然后,当加载处理程序运行时,它会获取 queue
中已有的所有内容。并将其输出到results
设置之前的元素queue
为空:
results.innerHTML = queue.join('');
queue = null;
任何调用assert()
的电话之后文档加载后会发现if (queue)
是假的,因为 queue
为空,所以else
将被执行,任何结果将直接输出到 results
元素。
在如图所示的代码中,只有一次对 assert()
的调用它会在文档加载处理程序运行之前发生。
(这是一个笨拙的演示 - 按下按钮将在加载事件之后:http://jsfiddle.net/JDFuR/1/)
关于javascript - 我试图找到这段代码中的错误,测试我的 javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014611/