javascript - 为什么这个JS循环重写整个页面

标签 javascript html loops

我有一个网页,它有一个循环来写出一堆列表元素。 加载时,for 循环运行 56 次,并使用 CSS 样式等。

但是,我有一个运行 loops() 函数的输入按钮,该函数运行 do 代码块,这基本上会使用新列表重新加载页面,但没有我的其他 html 出现了。

如何制作一个 loops() 来添加我的列表元素并增加列表而不是重新加载整个文档?

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <link rel="stylesheet" href="jscss.css">
 <script src="js.js"></script>
</head>
<body>
  <script>
  function loops(){
    var i= 0;
 do{
   document.write("<li id='list'>"+i+"</li>");
    i++;
  }while(i < 100);
  }
  document.write("Hello World");
  document.write("<br>");
  document.write("<input id='string' type='text'>");
  document.write("<input onClick='loops()' type='button'  value='Submit'>");
 document.write("<ul id='list'>");
 for (i = 0; i <= 56; i++) {
    document.write("<li>"+i+"</li>");
};
document.write("</ul>");
    </script>

最佳答案

因为调用document.write文档加载后会清除文档。

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.

因此,当您单击按钮时,文档已经加载,因此正在被清除。

您可以使用appendChild()或将新内容添加到父元素的innerHTML

function loops() {
  var i = 0,
    lst = document.getElementById('list'),
    html = '';
  do {
    html += "<li>" + i + "</li>";
  } while (++i < 100);
  lst.innerHTML += html;
}
document.write("Hello World");
document.write("<br>");
document.write("<input id='string' type='text'>");
document.write("<input onClick='loops()' type='button'  value='Submit'>");
document.write("<ul id='list'>");
for (i = 0; i <= 56; i++) {
  document.write("<li>" + i + "</li>");
};
document.write("</ul>");

关于javascript - 为什么这个JS循环重写整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32961612/

相关文章:

html - 文字阴影 : IE8

javascript - 遍历子节点

javascript - 移动应用程序中的 Ghostclicks

javascript - Bootstrap 对话框未在其中执行 JavaScript 代码

javascript - 使用 css 过渡从屏幕平移时如何消除反弹效果?

c - 如何加速我的代码?

java - 为什么在Java中改变for循环计数器是不好的?

javascript - 使用 javascript 定期更新文本框

javascript - 如何解析 C# 代码然后将其序列化回文本文件

html - 图像下方的颜色条出现