我可以'Don’我不想让我的程序继续下去;m使用document.write,因为它在html中使用JavaSc

I can't get my program to go down a line and I'm using document.write because its in html using JavaScript

本文关键字:因为 write document html JavaSc 使用 我不想 Don 我的 我可以 继续      更新时间:2023-09-26

我是编程新手,正在努力学习如何使用JavaScript。我书中的问题是,我必须在html页面中使用循环来编写程序,但它们都在同一行。

这就是程序:

<html>
<body>
    <script>
    var sheepCounted = 0;   
    while (sheepCounted < 10) {
        document.write("I have counted " + sheepCounted + " sheep!");
    sheepCounted++;   
    }
    </script>
</body>
</html>

但它所返回的只是:

I have counted 0 sheep!I have counted 1 sheep!I have counted 2 sheep!I have counted 3 sheep!I have counted 4 sheep!I have counted 5 sheep!I have counted 6 sheep!I have counted 7 sheep!I have counted 8 sheep!I have counted 9 sheep!

(全部在线)

我在这个代码上也有问题我的第一个正确HTML页面

<body>
    <h1>Hello</h1>
    <p>My First web page.</p>
    <script>
    var name = "Nick ";
    document.write("Hello, " + name);
    if (name.length > 7) {
      document.write("Wow, you have a REALLY long name!");
    }
        else {
            document.write("Your name isnt very long")
        }
    </script>
 </body>
 </html>

请帮帮我!!!!!

首先,不建议使用document.write。您应该进行DOM操作。但是,由于您是编程新手,所以我们不要这么做。

HTML中的所有空白,即制表符、换行符和空格,都被截断为一个空格。为了在页面上实际获得换行符,请使用标记<br />。或者,您可以将每个文本设置为一个段落,这样在语义上更有意义。要做到这一点,只需像<p>text</p> 一样将文本包装在<p>标签中

document.write("<p>I have counted " + sheepCounted + " sheep!</p>");

这也适用于你的第二个问题。只需用<p>文本<p>


如果您想使用DOM操作,请执行以下代码。请注意,这是一个更先进的,可以使用document.write,同时采取你的宝宝步骤

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <script>
        document.addEventListener("DOMContentLoaded", function() {
            for (var i = 0; i < 10; i++) {
                var p = document.createElement("p");
                p.textContent = "I have counted " + i + " sheep!";
                document.body.appendChild(p);
            }
        });
        </script>
    </body>
</html>

你几乎做到了。你只需要在"sheep!"之后添加一个<br />元素来强制换行:

....
<script>
var sheepCounted = 0;   
while (sheepCounted < 10) {
    document.write("I have counted " + sheepCounted + " sheep! <br />");
sheepCounted++;   
}
</script>
...