Dom操作高级应用
table
tBodies,tHead,tFoot,rows,cells
一个table有多个tbody
oTab.tBodies[0].rows[i].style.background = "#ccc";
示例:隔行换色
window.onload = function(){
var oTab = document.getElementById("tab1");
var oldColor; //关键点:保存行的旧样式
oTab.tBodies[0].rows[0].cells[1].innerHTML = "jack";
for(var i=0; i<oTab.tBodies[0].rows.length; i++){
if(i%2==0){
oTab.tBodies[0].rows[i].style.background = "#ccc";
}
else{
oTab.tBodies[0].rows[i].style.background = "";
}
oTab.tBodies[0].rows[i].onmouseover = function(){
oldColor = this.style.background; //保存行的旧样式
this.style.background = "green";
}
oTab.tBodies[0].rows[i].onmouseout = function(){
this.style.background = oldColor;
}
}
}
添加删除行
+++++++++++++++++++++++++++++++++++++++
window.onload = function(){
var oTab = document.getElementById("tab1");
var oName = document.getElementById("txtName");
var oAge = document.getElementById("txtAge");
var oBtn = document.getElementById("btn1");
var maxId = oTab.tBodies[0].rows.length + 1; //第一种
oBtn.onclick = function(){
var oTr = document.createElement("tr");
var oTd1 = document.createElement("td");
var oTd2 = document.createElement("td");
var oTd3 = document.createElement("td");
var oTd4 = document.createElement("td");
//var oA = document.createElement("a");
var length =oTab.tBodies[0].rows.length;
//var maxId =oTab.tBodies[0].rows[length-1].cells[0].innerHTML; //第二种
//oTd1.innerHTML = parseInt(maxId) + 1;
oTd1.innerHTML = maxId++;
oTd2.innerHTML = oName.value;
oTd3.innerHTML = oAge.value;
oTd4.innerHTML = '<a href="javascript:;">删除</a>';
/*
oA.innerHTML = "删除";
oA.setAttribute("href","javascript:;");
oTd4.appendChild(oA);
*/
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
oTr.appendChild(oTd3);
oTr.appendChild(oTd4);
////异常: 删除新添加行正常,删除旧行不正常
oTd4.getElementsByTagName("a")[0].onclick=function(){
oTab.tBodies[0].removeChild(this.parentNode.parentNode);
}
oTab.tBodies[0].appendChild(oTr);
}
// 异常:新添加的行不能删除
var aA = oTab.tBodies[0].getElementsByTagName("a");
for(var i=0; i<aA.length; i++){
aA[i].onclick = function(){
oTab.tBodies[0].removeChild(this.parentNode.parentNode);
}
}
}
表格搜索
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
window.onload = function(){
var oTxt = document.getElementById("txt1");
var oBtn = document.getElementById("btn1");
var oTab = document.getElementById("tab1");
oBtn.onclick = function(){
for(var i=0; i<oTab.tBodies[0].rows.length; i++){
var oRow = oTab.tBodies[0].rows[i];
var vTd = oRow.cells[1].innerHTML;
//if(oTxt.value == vTd){
//if(vTd.search(oTxt.value) != -1){ //模糊搜索str.search()
//if(vTd.toLowerCase().search(oTxt.value.toLowerCase()) != -1){ //模糊搜索str.search() + 忽略大小写
//关联搜索 如“张,李”
var arr = oTxt.value.split(',');
oRow.style.background = "";
for(var j=0; j<arr.length; j++){ //这里不能再定义i,否则会出问题
if(vTd.toLowerCase().search(arr[j].toLowerCase()) != -1){ //模糊搜索str.search() + 忽略大小写
oRow.style.background = "green";
}
}
}
}
}