HTML DOM
圖片翻轉效果<img src="button_off.gif"
onmouseover="this.src='button_over.gif';"
onmousedown="this.src='button_down.gif';"
onmouseout ="this.src='button_off.gif';"
onmouseup ="this.src='button_over.gif';">
動態添加移除頁面上的連絡人
var inputs = 0;
function addContact(){
var table = document.getElementById('contacts');
var tr = document.createElement('TR');
var td1 = document.createElement('TD');
var td2 = document.createElement('TD');
var td3 = document.createElement('TD');
var inp1 = document.createElement('INPUT');
var inp2 = document.createElement('INPUT');
if(inputs>0){
var img = document.createElement('IMG');
img.setAttribute('src', 'delete.gif');
img.onclick = function(){
removeContact(tr);
}
td1.appendChild(img);
}
inp1.setAttribute("Name", "Name" +inputs);
//same as element.name="elementName"
inp2.setAttribute("Name", "Email"+inputs);
table.appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
td2.appendChild(inp1);
td3.appendChild(inp2);
inputs++;
}
function removeContact(tr){
tr.parentNode.removeChild(tr);
}
<table>
<tbody id="contacts">
<tr>
<td colspan="3"><a href="javascript:addContact();">Add a Contact</a></td>
</tr>
<tr>
<td></td>
<td>Name</td>
<td>Email</td>
</tr>
</tbody>
</table>
我們可以利用childNodes訪問子項目,childNodes返回當前元素的子項目數組.也可以用firstChild和lastChild屬性訪問.
設定表格行顯示交替顏色function setColors(tbody, color1, color2){
var colors = [color1, color2];
var counter = 0;
var tr = tbody.firstChild;
while(tr){
tr.style.backgroundColor = colors[counter++ % 2];
tr = tr.nextSibling;
//returns the next element in the DOM with the same parent as the current element.
}
}
function setColors(tbody, color1, color2){
var colors = [color1, color2];
for(var i=0; i<tbody.childNodes.length; i++){
tbody.childNodes[i].style.backgroundColor = colors[i % 2];
}
}
function setColors(tbody, color1, color2){
var colors = [color1, color2];
var trs = tbody.getElementsByTagName('TR');
for(var i=0; i<trs.length; i++){
trs[i].style.backgroundColor = colors[i % 2];
}
}
getElementsByTagName:返回一個數組,包含具有相同tag名的所有元素
處理文本
頁面中的每段文本都被壓縮在一個隱藏的#text node中<div id="ourTest">this is <a href="link.html">a link</a> and an image: <img src="img.jpg"></div>
具有4個根項目 一個文本節點"this is" 一個具有子節點值為"a link"的節點 另外一個文本節點"and an image:" 一個圖片元素
改變"and an image:"值document.getElementById('ourTest').childNodes[2].nodeValue = 'our new text';
訪問"a link"值document.getElementById("ourTest").childNodes[1].childNodes[0].nodeValue;
加div中加入新的常值內容var newText = document.createTextNode('our new text');
var ourDiv = document.getElementsById('ourTest');
ourDiv.insertBefore(newText, ourDiv.childNodes[1]);
insertBefore接收兩個參數:待添加的元素和現有的元素 將待添加的元素添加到現有元素的前面Created by jecray