javascript表格操作大全:表格排序/倒序、動態添加列、大量刪除、刪除一行、隔行變色、滑鼠懸浮切換背景色、全選/反選。(IE、Firefox都相容)

來源:互聯網
上載者:User


表格.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>表格操作</title><script type= "text/javascript" src="domutil.js" ></script></head><body>  <!--以下資料純屬虛構--><table id="tab" border="1" style =" align:center;text-align:center "><thead style="background:#0000FF" onmouseover="over(this)" onmouseout="out(this)"><tr><th><input type="checkbox" name="quan" onclick="quan()" style="cursor:pointer"/>全選</th><th onclick="sortTable('tab',1,'int')" style="cursor:pointer">編號</th><th onclick="sortTable('tab',2,'漢字')" style="cursor:pointer">程式設計語言</th><th onclick="sortTable('tab',3,'漢字')" style="cursor:pointer">所屬公司</th><th onclick="sortTable('tab',4,'float')" style="cursor:pointer">市場份額</th><th onclick="sortTable('tab',5,'date')" style="cursor:pointer">誕生日期</th><th style="cursor:pointer">操作</th></tr></thead><tbody id="tbody"><tr style="background:#00FF00" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">4</td><td id="name" width="100">Java</td><td id="company" width="100" >甲骨文公司</td><td id="age" width="100">47.6</td><td id="date" width="100">1970/09/09</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr><tr style="background:#00FFFF" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">6</td><td id="name" width="100">ASP</td><td id="company" width="100">微軟公司</td><td id="age" width="100">30.3</td><td id="date" width="100">1980/09/09</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr><tr style="background:#00FF00" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">3</td><td id="name" width="100">PHP</td><td id="company" width="100">公司Zend</td><td id="age" width="100">22.1</td><td id="date" width="100">1994/07/09</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr><tr style="background:#00FFFF" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">1</td><td id="name" width="100">Objective-C</td><td id="company" width="100" >Stepstone公司</td><td id="age" width="100">35.9</td><td id="date" width="100">1980/01/01</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr><tr style="background:#00FF00" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">5</td><td id="name" width="100">VB</td><td id="company" width="100">美國微軟</td><td id="age" width="100">32.7</td><td id="date" width="100">1991/09/09</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr><tr style="background:#00FFFF" onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="checkbox" /></td><td width=100 id="ID">2</td><td id="name" width="100">javascript</td><td id="company" width="100">Netscape</td><td id="age" width="100">33.8</td><td id="date" width="100">1992/06/09</td><td ><input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)"/></td></tr></tbody><tfoot style="background:#C0C0C0"><tr onmouseover="over(this)" onmouseout="out(this)"><td><input type="checkbox" name="fan" onclick="fan()"/>反選</td><td colspan="6"><input type="button" value="添加資料" onclick="addRow()" />     <input type="button" value="刪除選中行" onclick="deleteChecked()"/></td></tr></tfoot></table></body> <script type="text/javascript"> /*全域變數ID:    儲存插入資料的編號color:儲存原來的背景色*/var ID,color;window.onload = function(){var myTab = $q("#tab");ID = myTab.rows.length-1;}//滑鼠懸浮在某元素時function over(node){color = node.style.backgroundColor;node.style.backgroundColor = '#FF00FF';}//滑鼠離開某元素時function out(node){node.style.backgroundColor = color;}//全選function quan(){var checkArr = $q("$checkbox"); //得到tbody行的集合var qArr = $q("$quan"); if(qArr[0].checked){ //如果是全選,設定全部選中for(var i=0;i<checkArr.length;i++){ checkArr[i].checked = true;}}else{  //如果沒有全選,設定全部沒選中for(var i=0;i<checkArr.length;i++){checkArr[i].checked = false;}}}//反選function fan(){var checkArr = $q("$checkbox"); //得到tbody行的集合for(var i=0;i<checkArr.length;i++){//迴圈將所有行反選checkArr[i].checked = checkArr[i].checked ? false : true;}}//添加一行資料function addRow(){var myTab = $q("#tab");var rowLength = myTab.rows.length;var newRow = document.createElement("tr"); //建立一行//設定隔行變色if(rowLength%2 == 1){newRow.style.background = "#00FFFF";}else{newRow.style.background = "#00FF00";}if(newRow.addEventListener){//給建立的行添加滑鼠懸浮的事件newRow.addEventListener("mouseover",function(){over(newRow);},false);//給建立的行添加滑鼠離開的事件newRow.addEventListener("mouseout",function(){out(newRow);},false);}else if(newRow.attachEvent){//給建立的行添加滑鼠懸浮的事件newRow.attachEvent("onmouseover",function(){over(newRow);});//給建立的行添加滑鼠離開的事件newRow.attachEvent("onmouseout",function(){out(newRow);});}else{//給建立的行添加滑鼠懸浮的事件newRow.onmouseover = function(){over(newRow);};//給建立的行添加滑鼠離開的事件newRow.onmouseout = function(){out(newRow);};}  //建立多列var newCell1 = document.createElement("td");newCell1.innerHTML = '<input type="checkbox" name="checkbox" />';var newCell2 = document.createElement("td");newCell2.innerHTML = ID;ID += 1;var newCell3 = document.createElement("td");newCell3.innerHTML = prompt("請輸入程式設計語言:","");var newCell4 = document.createElement("td");newCell4.innerHTML = prompt("請輸入所屬公司:","");var newCell5 = document.createElement("td");newCell5.innerHTML = prompt("請輸入市場份額:","");var newCell6 = document.createElement("td");newCell6.innerHTML = prompt("請輸入誕生日期:","");var newCell7 = document.createElement("td");newCell7.innerHTML = '<input type="button" value="刪除" onclick="deleteRow(this.parentNode.parentNode)" />' ;//將建立的多列添加到行newRow.appendChild(newCell1);newRow.appendChild(newCell2);newRow.appendChild(newCell3);newRow.appendChild(newCell4);newRow.appendChild(newCell5);newRow.appendChild(newCell6);newRow.appendChild(newCell7);var tbody = myTab.tBodies[0]; //擷取表格的tbodytbody.appendChild(newRow);  //將建立的行添加到表格body裡} //刪除一行資料function deleteRow(currentRow){var tab = $q("#tab"); //獲得表格節點tab.deleteRow(currentRow.rowIndex); //刪除選中的行}//刪除多行資料function deleteChecked(){var tab = $q("#tab"); //獲得表格節點var checkArr = $q("$checkbox");  //得到tbody行的集合for(var i=0;i<checkArr.length;i++){if(checkArr[i].checked){  //用迴圈刪除選中的行var index = checkArr[i].parentNode.parentNode.rowIndex;tab.deleteRow(index);}}}//轉換資料類型,v為值,dataType為資料類型function convert(v,dataType){switch(dataType){case "int":return parseInt(v);case "float":return parseFloat(v);case "date":return (new Date(Date.parse(v)));default:return v.toString();}}//排序函數,index為索引,type為資料類型function pai(index,dataType){if(dataType === "漢字"){return function compare(a,b){var str1 = convert(a.cells[index].innerHTML,dataType); var str2 = convert(b.cells[index].innerHTML,dataType);return str1.localeCompare(str2);};}else{return function compare(a,b){//var str1 = convert(a.cells[index].firstChild.nodeValue,dataType);//var str2 = convert(b.cells[index].firstChild.nodeValue,dataType);var str1 = convert(a.cells[index].innerHTML,dataType); //兩種方法效果一樣var str2 = convert(b.cells[index].innerHTML,dataType);if(str1 < str2){return -1;}else if(str1 > str2){return 1;}else{ return 0;}};}}//排序的過程function sortTable(tableID,index,dataType){var tab = $q("#"+tableID); //擷取表格的IDvar td = tab.tBodies[0]; //擷取表格的tbodyvar newRows = td.rows;   //擷取tbody裡的所有行var arr = new Array();   //定義arr數組用於存放tbody裡的行//用迴圈將所有行放入數組for(var i=0;i<newRows.length;i++){arr.push(newRows[i]);}//判斷最後一次排序的列是否與現在要進行排序的列相同,如果是就反序排列if(tab.sortCol == index){arr.reverse();}else{ //使用數組的sort方法,傳進排序函數arr.sort(pai(index,dataType));}var oFragment = document.createDocumentFragment(); //建立文檔片段            for (var i=0; i < arr.length; i++) {  //把排序過的aTRs數群組成員依次添加到文檔片段if(i%2 == 1){arr[i].style.background = "#00FFFF";oFragment.appendChild(arr[i]);}else{arr[i].style.background = "#00FF00";oFragment.appendChild(arr[i]);}}            td.appendChild(oFragment); //把文檔片段添加到tbody,完成排序後的顯示更新            tab.sortCol = index;  //記錄最後一次排序的列索引}</script></html>

domutil.js

(此js為課堂筆記整理而成,有部分代碼本次沒有用到的)

var CustomFunctions = {//擷取子節點的集合(ie,ff通用)getChildNodes:function(node){var arr = [];var nodes = node.childNodes;for(var i in nodes){if(nodes[i].nodeType == 1){ //尋找元素節點arr.push(nodes[i]);}}return arr;},//擷取第一個元素子節點(ie,ff通用)getFirstElementChild : function(node){return node.firstElementChild ? node.firstElementChild : node.firstChild ;},//擷取最後一個元素子節點(ie,ff通用)getLastElementChild : function(node){return node.lastElementChild ? node.lastElementChild : node.lastChild ;},//擷取上一個相鄰節點(ie,ff通用)getPreviousSibling : function(node){//找到上一個節點就返回節點,沒找到就返回nulldo{node = node.previousSibling;}while(node && node.nodeType!=1)return node;},//擷取下一個相鄰節點 (ie,ff通用)getNextSibling : function(node){//找到下一個節點就返回節點,沒找到就返回nulldo{node = node.nextSibling;}while(node && node.nodeType!=1)return node;},//將元素插入到指定的node節點後面insertAfter : function(newNode,targetNode){if(newNode && targetNode){var parent = targetNode.parentNode;var nextNode = this.getNextSibling(targetNode);if(nextNode && parent){parent.insertBefore(newNode,nextNode);}else{parent.appendChild(newNode);}}}};/*清除字串前後的空格*/String.prototype.trim=function(){return this.replace(/^\s*|\s*$/,"");};/*尋找元素:$q("div"):bytagname$q(".l"):byclassname$q("#l"):byid$q("$name"):bynameselector:選擇符parentElement:父元素*/window.$q = function(selector,parentElement){if(selector && (typeof selector) === 'string'){selector = selector.trim();//去掉前後空格var parentEl = parentElement || document;var nodeArr = new Array();var firstChar = selector.substr(0,1);//取得第一個字元//以#開頭,表示根據ID尋找if(firstChar === '#'){return parentEl.getElementById(selector.substr(1));}//以$開頭,根據name尋找else if(firstChar === '$'){var all = parentEl.getElementsByTagName("*");for(var i=0;i<all.length;i++){var name = all[i].getAttribute("name");if(name === selector.substr(1)){nodeArr.push(all[i]);}}delete i;return nodeArr;}//以.開頭,根據class名尋找else if(firstChar === '.'){var className = selector.substr(1);if(parentEl.getElementsByClassName){return parentEl.getElementsByClassName(className);}else{var childList = parentEl.getElementsByTagName("*");for(var i=0;i<childList.length;i++){var nodeClassName = childList[i].className;var classNameArr = nodeClassName.split(' ');for(var j=0;j<classNameArr.length;j++){if(classNameArr[j]===className){nodeArr.push(childList[i]);}}delete j;}delete i;return nodeArr;}}//否則,根據標籤名尋找else{return parentEl.getElementsByTagName(selector);}}else{return document.all || document.getElementsByTagName("*");}};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.