[英]Why do I have this text “undefined” in my html file after I execute some javascript in script tag?
I am executing some java script in an if/else block that prints some tags/content to the html file using document.write() function. 我在if / else块中执行一些Java脚本,该脚本使用document.write()函数将一些标签/内容打印到html文件中。 This piece of javascript is within the "script" tag just before I end the "body" tag. 在我结束“ body”标签之前,这段javascript位于“ script”标签内。 But I see a very weird behaviour: when my if() condition satisfies, I see some extra text "undefined" in the html. 但是我看到了一个非常奇怪的行为:当我的if()条件满足时,我在html中看到了一些额外的文本“ undefined”。 I am not writing this undefined text using JS. 我没有使用JS编写此未定义的文本。 At the same time when the code within else {} block gets executed, this undefined text does not appear anymore in my html file. 同时执行else {}块中的代码时,这个未定义的文本不再出现在我的html文件中。 The strcture of my code is as follows: 我的代码的结构如下:
if(){}
else{
if(){
html_text += "<div><p>hello world</p></div>";
document.write(html_text);
} else {
html_text += "<div><p>No hello world</p></div>";
document.write(html_text);
}
}
That is because you have never initialized the variable html_text
. 这是因为您从未初始化变量html_text
。
<script>
var html_text = "";
// Other code
html_text += "<div><p>hello world</p></div>";
Do everything in right syntax and initial variable before concatenating. 连接前,请使用正确的语法和初始变量进行所有操作。
<script>
var html_text = "";
if(your_condition){
html_text += "<div><p>hello world</p></div>";
document.write(html_text);
}
else
{
html_text += "<div><p>No hello world</p></div>";
document.write(html_text);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.