为什么即使没有调用显式打印方法(例如document.write),函数的返回值也会打印?
Why does the return value of a function print even though no explicit printing method is called (ex. document.write)?
我几天前刚开始使用javascript,正在尝试不同的方法来打印函数的返回值。
<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());
然而,这是不正确的,导致未定义的输出
将元素的innerHTML
设置为字符串会导致该元素的HTML被更改为该字符串。
document.getElementById('mySpan').innerHTML=produceMessage();
- 呼叫
produceMessage()
- 设置id为
mySpan
的元素的innerHTML为result
您的函数produceMessage
返回一个字符串,因此该元素的innerHTML设置为This should print
。
你的下一个语句,
document.getElementById('mySpan').innerHTML=document.write(produceMessage());
-
produceMessage()
- 用结果调用
document.write()
,将This should print
追加到文档 - 设置id为
mySpan
的元素的innerHTML为document.write
的返回值
document.write
返回undefined
,因此该元素的innerHTML被设置为undefined
的字符串表示。
相关文章:
- ko.com在foreach$data变量上添加了write函数
- 如何在使用函数document.write()打印最终结果后,使用Javascript滚动到页面顶部
- 无法运行php函数来使用document.write更新db值
- 如何在 document.write 中调用 onclick 函数
- document.write 和 innerHTML 在函数调用中
- 有没有办法在javascript中克隆本机函数,如window.alert或document.write
- 在 setTimeout 中调用 document.write 之后,“函数未定义”
- 通过 Response.Write() 写回函数
- 如何使用node.js的fs.write函数
- 当我通过Jquery.post()传递主函数时,Response.Write函数不起作用
- 当我使用document.write函数在下面的代码中打印数字时,它会在每个输出的右侧插入0.为什么会发生这种事
- document.write在函数体中
- JS document.write函数并打印字符^
- Javascript函数,如何取document.write中的变量
- Javascript document.write(onclick)引用错误未定义函数
- 使用QUnit测试使用document.write()的实用程序函数:使文档对象成为其他文档
- 返回document.write内的Javascript函数('
- response.write在回调函数中
- 无法在“document.write();”中启动函数
- 为什么即使没有调用显式打印方法(例如document.write),函数的返回值也会打印?