document.write() 可用于直接向 HTML 輸出流寫(xiě)內(nèi)容,簡(jiǎn)單的說(shuō)就是直接在網(wǎng)頁(yè)中輸出內(nèi)容。
第一種:輸出內(nèi)容用""括起,直接輸出""號(hào)內(nèi)的內(nèi)容,補(bǔ)充:如果是數(shù)字,有無(wú)""均可;如果是漢字與字母必須添加
1 <script type="text/javascript">
2 document.write("I love JavaScript!"); //內(nèi)容用""括起來(lái),""里的內(nèi)容直接輸出。
3 </script>
1 <script type="text/javascript">
2 //document.write(1 2 3)
3 /*
4 document.write()輸出內(nèi)容,如果是數(shù)字就不要添加""不過(guò)要是這樣的話,你輸出的數(shù)字中有空格,就報(bào)錯(cuò)了,所以糾正下,還是老老實(shí)實(shí)寫(xiě)上這個(gè)"" 5 */
6 </script>
第二種:通過(guò)變量,輸出內(nèi)容
1 <script type="text/javascript">
2 var mystr="hello world!"; 3 document.write(mystr); //直接寫(xiě)變量名,輸出變量存儲(chǔ)的內(nèi)容。
4 </script>
第三種:輸出多項(xiàng)內(nèi)容,內(nèi)容之間用+號(hào)連接
專門(mén)建立的學(xué)習(xí)Q-q-u-n: 784783012 ,分享學(xué)習(xí)的方法和需要注意的小細(xì)節(jié),不停更新最新的教程和學(xué)習(xí)技巧
(從零基礎(chǔ)開(kāi)始到前端項(xiàng)目實(shí)戰(zhàn)教程,學(xué)習(xí)工具,全棧開(kāi)發(fā)學(xué)習(xí)路線以及規(guī)劃)
1 <script type="text/javascript">
2 var mystr="hello"; 3 document.write(mystr+"I love JavaScript"); //多項(xiàng)內(nèi)容之間用+號(hào)連接
4 </script>
第四種:輸出HTML標(biāo)簽,并起作用,標(biāo)簽使用""括起來(lái)
1 <script type="text/javascript">
2 var mystr="hello"; 3 document.write(mystr+"<br>");//輸出hello后,輸出一個(gè)換行符
4 document.write("JavaScript"); 5 </script>
完整代碼展示:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>JavaScript-輸出內(nèi)容(document.write)</title>
6 <script type="text/javascript">
7 //第一種
8 document.write("說(shuō)什么好了,糾結(jié),那就不說(shuō)了")
9 //第二種
10 var sky="i love javascript"
11 document.write(sky); 12 //第三種
13 var mystr="hello"; 14 document.write(mystr+123+"girl妹子"); 15 //第四種
16 var boy="95 boy"; 17 document.write("<br/>"+"在"+2020+"年"+boy+" "+"prefect javascript") 18 </script>
19 </head>
20 <body>
21 <!-- <form action="" method=""> 22 <input type="button" name="" id="" value="點(diǎn)我" onclick="hs()"/> 23 </form> 24 <script type="text/javascript"> 25 function hs(){ 26 alert("調(diào)用函數(shù)"); 27 } 28 hs(); 29 </script> -->
30 </body>
31 </html>
||知識(shí)拓展:js中如何輸出空格
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>js中如何輸出空格</title>
6 <script type="text/javascript">
7 document.write("1 2 3");
8 /*
9 無(wú)論在輸出的內(nèi)容中什么位置有多少個(gè)空格,顯示的結(jié)果好像只有一個(gè)空格。
10 這是因?yàn)闉g覽器顯示機(jī)制,對(duì)手動(dòng)敲入的空格,將連續(xù)多個(gè)空格顯示成1個(gè)空格。
11 */
12 //解決辦法一:使用輸出html標(biāo)簽 來(lái)解決,這里讓我想到html的文本空格
13 document.write("<br/>"+"1"+" "+"2 3");
14 //解決辦法二:使用CSS樣式來(lái)解決, 注意在輸出時(shí)添加“white-space:pre;”樣式屬性,這個(gè)樣式表示"空白會(huì)被瀏覽器保留"
15 document.write("<p style='white-space: pre;'>"+"1 2 3"+"</p>");
16 document.write("<p style='letter-spacing: 20px;'>"+"123"+"</p>");
17 document.write("<p style='word-spacing:20px;'>"+"who care about you 'Your pressure comes from'"+"b"+"c"+"</p>");
18 </script>
19 </head>
20 <body>
21 </body>
22 </html>