DIV CSS 佈局教程網

JavaScript 使用 appendChild 動態追加節點實戰
編輯:關於JavaScript     

本文示範如何運用 JavaScript 的 appendChild 方法,在 DOM 樹中動態新增節點。

新增節點的實作範例

<html>
<head>
<script type="text/javascript">
function t(){
  var nodep = document.createElement('p');    // 建立 p 節點
  var art = document.createTextNode('你好,世界'); // 建立文字節點

  var cont = document.getElementById('container'); // 取得目標容器
  cont.appendChild(nodep);   // 將 p 節點加入容器
  nodep.appendChild(art);    // 將文字節點加入 p 節點
}
</script>
<style type="text/css">
p{width:100px;height:100px;background:green;}
#container p{width:100px;height:100px;background:blue;}
</style>
</head>
<body>
<div id="container"><p>hello world</p></div>
<p>說兩句吧</p>
<hr />
<button onclick="t()" value="">增加節點</button>
</body>
</html>

透過 createElement 建立元素、createTextNode 建立文字,再用 appendChild 逐層掛載,就能輕鬆擴充頁面結構。希望本文對你的 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved