JavaScript HTML DOM——改變HTML
阿新 • • 發佈:2018-10-14
文檔加載 ntb var color test 中國 ttr 改變 page
HTML DOM 允許 JavaScript 改變 HTML 元素的內容。
1、改變 HTML 輸出流
JavaScript 能夠創建動態的 HTML 內容:
今天的日期是: Sun Oct 14 2018 17:06:00 GMT+0800 (中國標準時間)
在 JavaScript 中,document.write() 可用於直接向 HTML 輸出流寫內容。
提示:絕不要使用在文檔加載之後使用 document.write()。這會覆蓋該文檔。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <!--<meta charset="utf-8">--> 5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 6 <meta http-equiv="Content-Language" content="zh-cn" /> 7 <title>My test page</title> 8 9 </head> 10 11 <body>12 <script> 13 document.write(Date()); 14 </script> 15 </body> 16 </html>
輸出結果:Sun Oct 14 2018 17:15:26 GMT+0800 (中國標準時間)
2、改變 HTML 內容
修改 HTML 內容的最簡單的方法時使用 innerHTML 屬性。
如需改變 HTML 元素的內容,請使用這個語法:
1 document.getElementById(id).innerHTML=new HTML
舉例(本例改變了p元素的內容):
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <!--<meta charset="utf-8">--> 5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 6 <meta http-equiv="Content-Language" content="zh-cn" /> 7 <title>My test page</title> 8 9 </head> 10 11 <body> 12 13 <p id="p1">Hello, world!</p> 14 <script> 15 var x = document.getElementById("p1"); 16 x.innerHTML = "New text!" 17 </script> 18 </body> 19 </html>
輸出結果:New text!
3、改變 HTML 屬性
如需改變 HTML 元素的屬性,請使用這個語法:
1 document.getElementById(id).attribute=new value
舉例(本例改變了 <img> 元素的 src 屬性):
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <!--<meta charset="utf-8">--> 5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 6 <meta http-equiv="Content-Language" content="zh-cn" /> 7 <title>My test page</title> 8 9 </head> 10 11 <body> 12 13 <img id="image1" src=hello.jpg> 14 15 <script> 16 var x = document.getElementById("image1"); 17 x.src = "baidu.jpg"; 18 </script> 19 </body> 20 </html>
JavaScript HTML DOM——改變HTML