2015-02-08 26 views
0

我是编程新手,我正在学习如何做JavaScript。我书中的问题说我必须在我的html页面中使用循环编写程序,但它们都在同一行。我不能让我的程序下线,我使用document.write,因为它在html中使用JavaScript

这是程序:

<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> 

请帮助我!!!!!

+2

追加''
羊后'使用文件撰写!'。 FWIW,'document.write()'是一种向浏览器窗口输出数据的不好方法。铭记未来。 – 2015-02-08 22:09:58

+0

我是怎么卖的? – 2015-02-08 22:13:00

+0

我应该怎么做? – 2015-02-08 22:13:25

回答

2

首先,使用document.write不推荐。你应该做DOM操作。但是,由于您是编程新手,我们不要那样做。

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

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

这也适用于你的第二个问题。只是包装在<p>文本</P >


如果你想使用DOM操作,这样做下面的代码的文本。请注意,这是更先进一点,它的确定同时服用宝宝步骤

<!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> 
0

你已经差不多了。你只需要"sheep!"后添加<br />元素强制换行:

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

谢谢你,但你有第二个代码的答案吗? – 2015-02-08 22:12:00

+0

基本上是一样的东西。无论你想要换行,只需添加'
'。 – Eclecticist 2015-02-08 22:12:51

+0

你有第二个代码的答案吗? – 2015-02-08 22:14:06

相关问题