0
我刚刚在几天前开始使用JavaScript,并且正在用各种方式来打印函数的返回值。即使没有调用明确的打印方法(如document.write),为什么打印函数的返回值?
<script>
function produceMessage(){
var msg= 'This should print';
return msg;
}
</script>
<span id="mySpan"></span>
这两行代码都会调用方法write或createTextNode来打印消息。
document.body.appendChild(document.createTextNode(produceMessage()));
document.write(produceMessage());
但是这行不会调用这样的方法,但返回值仍在打印。
document.getElementById('mySpan').innerHTML=produceMessage();
我的直觉告诉我,才能有返回值显示在屏幕上,你需要调用某种方法将允许它打印出来,就像这个例子:
document.getElementById('mySpan').innerHTML=document.write(produceMessage());
但是这是不正确的,并导致未定义的输出。
PS:不要在加载页面后使用document.write,因为它会擦除页面及其上的所有脚本 – mplungjan