获取html打印javascript函数返回值的首选语法是什么?
function produceMessage(){
var msg= 'Hello<br />';
return msg;
}
Run Code Online (Sandbox Code Playgroud)
编辑:Yikes,太多的答案没有我澄清我的意思.我知道如何通过脚本标签来做到这一点.但是,假设我想让消息变红.我会像这样将脚本标签包含在我的CSS中吗?
<div style="color:red><script>document.write(produceMessage())</script></div>
Run Code Online (Sandbox Code Playgroud)
我想我的主要问题是,你是否应该使用document.write来获取要打印的返回值?
Mat*_*zer 15
有一些选择可以做到这一点.
一个是:
document.write(produceMessage())
其他会以这种方式在文档中附加一些元素:
var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);
Run Code Online (Sandbox Code Playgroud)
要不就:
document.body.appendChild(document.createTextNode(produceMessage()));
Run Code Online (Sandbox Code Playgroud)
如果你正在使用jQuery,你可以这样做:
$(document.body).append(produceMessage());
Run Code Online (Sandbox Code Playgroud)
Max*_*axx 12
这取决于你的目标.我相信JS最接近的东西是:
document.write( produceMessage() );
Run Code Online (Sandbox Code Playgroud)
但是,将值放在您选择的范围或div中可能更为谨慎,例如:
document.getElementById("mySpanId").innerHTML = produceMessage();
Run Code Online (Sandbox Code Playgroud)