文档写入文档get元素

时间:2014-12-08 22:29:46

标签: javascript html css

我是JavaScript的新手,我想让它进入带有

的id输出的段落

但是,当我这样做时,我不会得到任何输出。

以下是代码,我想将所有document.write更改为document.getElementById('output').innerHTML = blablabla;

<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
<style type="text/css">
    body
    {
        background-color: black;
        color:springgreen;
        text-align: center;
    }
</style>
</head>
<body>
<p id="output"></p>
<script type="text/javascript">
    var names, i, next;
    names = new Array();
    i = 0;
    do {
        next = prompt("Please enter your name");

        if (next > " " && next != "undefined") names[i] = next;
        i++
    }
     while (next > " " && next != "undefined");
   document.write("<h2>" + (names.length) + " names written</h2>");
   document.write("<ol>");
   for (i in names) {
        document.write("<li>" + names[i] + "<br>")
   }
   document.write("</ol>");
</script>
</body>
</html>   

2 个答案:

答案 0 :(得分:1)

您不希望使用document.write,而是将每个部分附加到变量:

var outputHTML = "";
outputHTML += "<h2>"; // etc

然后使用document.getElementById('output').innerHTML = outputHTML;

设置您的内容

答案 1 :(得分:-1)

  var names, i, next;
  // This syntax is preferred
  names = []

  // No need to use a counter here
  do {
    next = prompt("Please enter your name");

    if (next) {
      names.push(next);
    }
  }
  while (next !== "");  // Loop until an empty string/blank input

  var out = [];
  out.push("<h2>" + (names.length) + " names written</h2>");
  out.push("<ol>");
  for (i in names) {
    out.push("<li>" + names[i] + "<br>");
  }
  out.push("</ol>");

  document.getElementById("output").innerHTML = out.join("");