document.write() 和 document.writeln() 區別


document.write()和document.writeln()有什么區別 
解決思路: 
    兩者都是JavaScript向客戶端輸出的方法,對比可知寫法上的差別是一個ln--line的簡寫,換言之,writeln 方法是以行輸出的,相當於在 winte 輸出后加上一個換行符。 
具體步驟: 
1.打開一個空白窗口。 
window.open() 
2.用 write 方法向空白窗口寫入代碼。 
document.write("Line 1") 
document.write("Line 1") 
3.用 writeln 方法向空白窗口寫入代碼。 
document.writeln("Line 1") 
document.writeln("Line 2") 
4.完整代碼示例: 

with(window.open()){ 
document.write("Line 1") 
document.write("Line 1") 
document.writeln("Line 1") 
document.writeln("Line 2") 
} 

注意:兩種方法僅當在查看源代碼時才看得出區別。 
特別提示 
把上面的代碼加入網頁中,然后查看彈出窗口的源代碼,將會看到: 
Line 1Line 1Line 1 
Line 2

ps:實際上多了空格而已 。沒有特別區分。

 

document.write()和document.writeln()的區別 + 用js寫動態select 
解決思路: 

兩者都是JavaScript向客戶端輸出的方法,對比可知寫法上的差別是一個ln--line的簡寫,換言之,writeln 方法是以行輸出的,相當於在?winte?輸出后加上一個換行符。 

注意:document.write方法可以用在兩方面:在網頁載入過程中用實時腳本創建網頁內容以及用延時腳本創建本窗口或新窗口的內容.該方法需要一個字符串參數,它是寫到窗口或框架中的HTML內容.該字符串參數可以是變量或值為字符串的表達式,寫入內容常常包含HTML標記. 

記住,載入網頁后,瀏覽器輸出流將自動關閉.在些之后任何一個對當前網頁的document.write()方法都將打開一個新的輸出流,它將清除當前網頁輸出內容(包括源文檔中的任何變是和值).因此,如果希望用腳本生成的HTML內容替換當前網頁,就必須把HTML內容連接起來賦給一個變量.這里,使用document.write()來完成寫操作.不必清除文檔並打開一個新的數據流,一個document.write()調用就OK了. 

關於document.write()方法,還需要說明它的相關方法document.close().腳本向窗口(不管是本窗口還是其它窗口)寫完內容后必須關閉輸出流.在腳本的最后一個document.write() 方法后面.必須確保有document.close()方法.不這樣做就不能顯示圖像和表單.而且,后面調用的任何document.write() 只會將內容追加到網頁后,而不會清除現有內容,寫入新值 

具體步驟: 

1.打開一個空白窗口。 
window.open() 

2.用 write 方法向空白窗口寫入代碼。 

document.write("Line1") 
document.write("Line1") 

3.用 writeln 方法向空白窗口寫入代碼。 

document.writeln("Line1") 
document.writeln("Line2") 

4.完整代碼示例: 

復制代碼代碼如下:
<script>   with(window.open()){  document.write("Line1")  document.write("Line1")  document.writeln("Line1")  document.writeln("Line2")  }  </script> 



注意:兩種方法僅當在查看源代碼時才看得出區別。 
特別提示:把上面的代碼加入網頁中,然后查看彈出窗口的源代碼,將會看到: 

Line1Line1Line1 
Line2 

頁面效果和源代碼如圖。 




特別說明 

總的來說,一般情況下用兩種方法輸出的效果在頁面上是沒有區別的(除非是輸出到pre或xmp元素內)。 

二、document.write()向指定位置寫html 
頁面初始化時可以正確寫在select框內 
但調用時就寫在控件外了 ,不知道document.write()能否想改變innerHTML或outerHTML來動態寫HTML?以及寫的HTML要用來顯示該如何處理? 

如下: 

復制代碼代碼如下:
<html>   <head></head>  <script type="text/javascript">  function creatOption(){  for(i=0;i<5;i++)  document.write("<option value='"+i+"'>"+i+"</option>");  }  function openWrite(){  var win=window.open();  win.document.write("Line1");  win.document.write("Line1");  win.document.write("<input type='text' value='1234567890' />");  win.document.writeln("Line1");  win.document.writeln("Line2");  }  </script>  <body>  <select id="myselect" name="myselect">  <script language="javascript">  creatOption();  </script>  </select>  <input type="button" value="按鈕" onclick="openWrite()"/>  </body>  </html> 



關於保留格式,測試一下:<script> document.write("<pre>我在pre中不會換行!")document.write("我在pre中不會換行!")document.writeln("我在pre中會換行!")document.writeln("我在pre中會換行!")document.writeln("我在pre中會換行!</pre>") </script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM