简体   繁体   English

在脚本标记中执行一些javascript后,为什么在html文件中有此文本“ undefined”?

[英]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.

相关问题 下载文件后如何执行一些JavaScript? - How do I execute some javascript after a file is downloaded? 我如何将我的 .env 文件链接到我的 html 文件并在脚本标签中使用它? - how do i link my .env file to my html file and use it in a script tag? 当我在<script> tag - My JavaScript file is not being called by the HTML file when I specify the type as module in the <script> tag 为什么当我调试我的值选项标签 html 时未定义? - Why when i debug my value option tag html is undefined? javaScript将一些标签动态添加到HTML后,我的设计按原样进行了更改,我该如何解决这个问题 - After javaScript dynamically added some tags to my HTML my design changed as it is, how do i fix this proplem 如何将 HTML 脚本标签复制到外部 javascript? - How do I copy HTML script tag to external javascript? 如何调试HTML脚本标记中编写的JavaScript - How do I debug JavaScript written within a script tag in the HTML 为什么我需要在HTML中注释<script>标记? - Why do I need to comment the <script> tag in HTML? <script> tag is not working i am trying to run javascript script in script tag in html file - <script> tag is not working i am trying to run javascript script in script tag in html file 前100个素数javascript,为什么我的素数数组后变得不确定? - First 100 primes javascript, why do I get undefined after my array of primes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM