我几天前刚开始使用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());然而,这是不正确的,并导致未定义的输出。
发布于 2011-08-06 15:51:25
将元素的innerHTML设置为字符串会导致该元素的超文本标记语言更改为该字符串。所以,
document.getElementById('mySpan').innerHTML=produceMessage();produceMessage()mySpan的元素的innerHTML以生成函数produceMessage返回一个字符串,因此该元素的innerHTML被设置为This should print。
你的下一份声明,
document.getElementById('mySpan').innerHTML=document.write(produceMessage());使用结果调用produceMessage()
This should print追加到document
mySpan的元素追加到document.write的返回值
document.write返回undefined,因此该元素的innerHTML被设置为undefined的字符串表示形式。
https://stackoverflow.com/questions/6965471
复制相似问题