您的位置:首页 > Web前端 > JavaScript

javascript学习笔记 (二)-DOM

2009-04-20 10:41 603 查看


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接收两个参数:待添加的元素和现有的元素 将待添加的元素添加到现有元素的前面
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: