javascript能增加標籤,方法:1、使用「document.createElement("標籤名")」語句建立新標籤節點;2、使用insertBefore()或appendChild()函數在指定子元素節點前或後插入新標籤節點。

本教學操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。
節點的插入分成兩種情況:在元素子節點清單的後面附加子節點和在元素某個子節點前面插入子節點:
範例1:在元素子節點清單的後面附加子節點
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
</head>
<body>
<ul id= "myList" >
<li>Coffee</li>
<li>Tea</li>
</ul>
<p id= "demo" >单击按钮将项目添加到列表中</p>
<button onclick= "myFunction()" >点我</button>
<script>
function myFunction() {
var node = document.createElement( "LI" );
var textnode = document.createTextNode( "Water" );
node.appendChild(textnode);
document.getElementById( "myList" ).appendChild(node);
}
</script>
</body>
</html>
|
登入後複製

注意:
先建立一個節點,
然後建立一個文字節點,
然後將文字節點新增到LI節點上。
最後將節點加入到清單中。
範例2:在元素某個子節點前面插入子節點
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
</head>
<body>
<ul id= "myList" >
<li>Coffee</li>
<li>Tea</li>
</ul>
<p id= "demo" >单击按钮插入一个项目列表</p>
<button onclick= "myFunction()" >点我</button>
<script>
function myFunction() {
var newItem = document.createElement( "LI" )
var textnode = document.createTextNode( "Water" )
newItem.appendChild(textnode)
var list = document.getElementById( "myList" )
list.insertBefore(newItem, list.childNodes[0]);
}
</script>
</body>
</html>
|
登入後複製

##注意:
- 先建立一個li節點,
- 然後建立一個文字節點,
- 然後加入文字節點的在li節點。
- 最後在第一個子節點清單插入li節點。
【相關推薦:
javascript學習教學】
以上是javascript能增加標籤嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!