您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關JS如何實現隔行換色的表格排序的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1、獲取元素 2、獲取數據 3、綁定數據 4、隔行換色 5、表格排序
<table cellpadding="0" cellspacing="0" id="tab"> <thead> <tr> <th class="cursor">姓名</th> <th class="cursor">年齡</th> <th class="cursor">分數</th> <th>性別</th> </tr> </thead> <tbody> <!--<tr class="bg0"> <td>趙老大</td> <td>45</td> <td>89</td> <td>0</td> </tr> <tr class="bg1"> <td>趙老大</td> <td>45</td> <td>89</td> <td>0</td> </tr>--> </tbody> </table> <script type="text/javascript" src="js/utils.js"></script> <script type="text/javascript" src="js/biaoge.js"></script>
css 樣式
*{ margin:0; padding:0; } table{ width: 800px; margin:50px auto; box-shadow: 0 0 10px #333; border-radius: 10px; overflow: hidden; font-size: 18px; } table thead tr{ text-align: center; width: 100%; height: 50px; background:#ffb4b4; } table thead th{ width: 200px; line-height: 50px; color: white; } table tbody tr{ height: 40px; line-height: 40px; text-align: center; } table tbody tr.bg0{ background: lightgoldenrodyellow; } table tbody tr.bg1{ background: lightgray; } .cursor{ cursor: pointer; }
JS
所用到的 util.js
var utils=(function(){ var flg='getComputedStyle' in window; // 惰性思想的運用; function makeArray(arg){ if(flg){ // 標準瀏覽器 return Array.prototype.slice.call(arg); }else{ var ary=[]; for(var i=0; i<arg.length; i++){ ary.push(arg[i]); } return ary; } } function jsonParse(jsonStr){ return 'JSON' in window?JSON.parse(jsonStr):eval('('+jsonStr+')'); } function rnd(n,m){ n=Number(n); m=Number(m); if(isNaN(n) || isNaN(m)){ return Math.random();//當返回0-1之間的隨機小數,說明參數傳錯了; } if(n>m){ var tmp=m; m=n; n=tmp; } return Math.round(Math.random()*(m-n)+n); } function getByClass(strClass,parent){ parent=parent||document; if(flg){ return this.makeArray(parent.getElementsByClassName(strClass)); } //對IE瀏覽器兼容處理; var aryClass=strClass.replace(/(^ +)|( +$)/g,'').split(/\s+/g); var nodeList=parent.getElementsByTagName('*'); var ary=[]; for(var i=0; i<nodeList.length; i++){ var cur=nodeList[i]; var bOk=true; for(var j=0; j<aryClass.length; j++){ var reg=new RegExp('(^| +)'+aryClass[j]+'( +|$)'); if(!reg.test(cur.className)){ bOk=false; break; } } if(bOk){ ary.push(cur); } } return ary; } function hasClass(curEle,cName){ var reg=new RegExp('(^| +)'+cName+'( +|$)','g'); return reg.test(curEle.className); } function addClass(curEle,strClass){ var aryClass=strClass.replace(/(^ +)|( +$)/g,'').split(/\s+/g); for(var i=0; i<aryClass.length; i++){ if(!this.hasClass(curEle,aryClass[i])){ curEle.className+=' '+aryClass[i]; } } } function removeClass(curEle,strClass){ var aryClass=strClass.replace(/(^ +)|( +$)/g,'').split(/\s+/g); for(var i=0; i<aryClass.length; i++){ var reg=new RegExp('(^| +)'+aryClass[i]+'( +|$)','g'); if(reg.test(curEle.className)){ curEle.className=curEle.className.replace(reg,' ').replace(/(^ +)|( +$)/g,'').replace(/\s+/g,' '); } } } function getCss(curEle,attr){ var val=null; var reg=null; if(flg){ val=getComputedStyle(curEle,false)[attr]; }else{ if(attr==='opacity'){ val=curEle.currentStyle['filter'];//‘alpha(opacity=10)'; reg=/^alpha\(opacity[=:](\d+(\.\d+)?)\)$/; return reg.test(val)?RegExp.$1/100:1; } val=curEle.currentStyle[attr]; } //如果帶單位了,干掉單位; reg=/^([+-])?(\d+(\.\d+)?)(px|pt|rem|em)?$/gi; return reg.test(val)?parseFloat(val):val; } function setCss(curEle,attr,value){ //升級3:處理float if(attr==='float'){ curEle.style.cssFloat=value; curEle.style.styleFloat=value; return; } //升級2:處理透明度 if(attr=='opacity'){ curEle.style.opacity=value; curEle.style.filter='alpha(opacity='+(value*100)+')'; return; } var reg=/(width|height|top|right|bottom|left|((margin|padding)(top|right|bottom|left)?))/gi; //升級1:處理單位; if(reg.test(attr)){ if(value!=='auto' || value.toString().indexOf('%') == -1){ value=parseFloat(value)+'px'; } } curEle.style[attr]=value; } function setGroupCss(curEle,opt){ if(Object.prototype.toString.call(opt) !== '[object Object]') return; for(var attr in opt){ this.setCss(curEle,attr,opt[attr]); } } function css(curEle){ var argTwo=arguments[1]; if(typeof argTwo==='string'){ var argThree=arguments[2]; if(argThree===undefined){//第三個參數沒有-獲取 return this.getCss(curEle,argTwo); }else{//當有第三個參數-設置一個樣式 this.setCss(curEle,argTwo,argThree); } } if({}.toString.call(argTwo)==='[object Object]'){ this.setGroupCss(curEle,argTwo); } } function win(attr,value){ if(value===undefined){ return document.documentElement[attr]||document.body[attr]; } document.documentElement[attr]=document.body[attr]=value; } function offset(curEle){ var l=curEle.offsetLeft; var t=curEle.offsetTop; var par=curEle.offsetParent; while(par){ if(window.navigator.userAgent.indexOf('MSIE 8') == -1){ l+=par.clientLeft; t+=par.clientTop; } l+=par.offsetLeft; t+=par.offsetTop; par=par.offsetParent; } return {left:l,top:t} } function getChildren(curEle,tagName){ var childs=curEle.childNodes;//獲取所有的子節點 var ary=[]; for(var i=0; i<childs.length; i++){ var cur=childs[i]; if(cur.nodeType==1){//首先保證是子元素,再考慮是否過濾; if(tagName){ if(cur.tagName.toLocaleLowerCase()===tagName.toLowerCase()){ ary.push(cur); } }else{ ary.push(cur) } } } return ary; } function prev(curEle){ if(flg){ return curEle.previousElementSibling; } var pre=curEle.previousSibling; while(pre && pre.nodeType !== 1){ pre=pre.previousSibling; } return pre; } function next(curEle){ if(flg){ return curEle.nextElementSibling; } var nex=curEle.nextSibling; while(nex && nex.nodeType !== 1){ nex=nex.nextSibling; } return nex; } function sibling(curEle){ var ary=[]; var pre=this.prev(curEle); var nex=this.next(curEle); if(pre) ary.push(pre); if(nex) ary.push(nex); return ary; } function prevAll(curEle){ var ary=[]; var pre=this.prev(curEle); while(pre){ ary.push(pre); pre=this.prev(pre); } return ary; } function nextAll(curEle){ var nex=this.next(curEle); var ary=[]; while(nex){ ary.push(nex); nex=this.next(nex); } return ary; } function siblings(curEle){ var ary1=this.prevAll(curEle); var ary2=this.nextAll(curEle); return ary1.concat(ary2); } function firstChild(curEle){ var children=this.getChildren(curEle); return children[0]; } function lastChild(curEle){ var children=this.getChildren(curEle); return children[children.length-1]; } function index(curEle){ return this.prevAll(curEle).length; } function appendChild(curEle,parent){ parent.appendChild(curEle); } function prependChild(curEle,parent){ var first=this.firstChild(parent); if(first){ parent.insertBefore(curEle,first); }else{ parent.appendChild(curEle); } } function insertBefore(curEle,oldEle){ oldEle.parentNode.insertBefore(curEle,oldEle); } function insertAfter(curEle,oldEle){ var nex=this.next(oldEle); if(nex){ oldEle.parentNode.insertBefore(curEle,nex); }else{ oldEle.parentNode.appendChild(curEle); } } return { //makeArray:類數組轉數組 makeArray:makeArray, //jsonParse:把JSON格式的字符串轉成JSON格式的數據(對象) jsonParse:jsonParse, //rnd:求一定范圍的隨機數,包含最大值; rnd:rnd, //getByClass:通過class名,可以限制范圍的獲取元素 getByClass:getByClass, //hasClass:判斷元素身上是否有某個class名 hasClass:hasClass, //addClass:給元素批量添加出class名 addClass:addClass, //removeClass:從元素身上批量刪除class名 removeClass:removeClass, //getCss:獲取非行間樣式 getCss:getCss, //setCss:給元素設置一個樣式 setCss:setCss, //setGroupCss:給元素設置一組樣式 setGroupCss:setGroupCss, //css:集獲取,設置一個,設置一組為一體; css:css, //win:瀏覽器盒子模型的兼容處理 win:win, //offset:元素偏移量的兼容處理; offset:offset, //getChildren:獲取當前元素下的所有子元素(可以通過標簽名過濾子元素) getChildren:getChildren, //prev:獲取當前元素的上一個哥哥元素 prev:prev, //next:獲取當前元素的下一個弟弟元素 next:next, //sibling:獲取當前元素的相鄰元素; sibling:sibling, //prevAll:獲取當前元素所有的哥哥元素 prevAll:prevAll, //nextAll:獲取當前元素所有的弟弟元素 nextAll:nextAll, //siblings:獲取當前元素所有的兄弟元素; siblings:siblings, //firstChild:獲取當前容器下第一個子元素 firstChild:firstChild, //lastChild:獲取當前容器下最后一個子元素 lastChild:lastChild, //index:當前元素的索引(當前元素排行第幾); index:index, //appendChild:把新元素插入到父容器的末尾; appendChild:appendChild, //prependChild:把新元素插入到父容器的開頭; prependChild:prependChild, //insertBefore:把新元素插入到指定元素的前面 insertBefore:insertBefore, //insertAfter:把新元素插入到指定元素的后面; insertAfter:insertAfter } })();
所用到的 biaoge.js
(function () { var oTab = document.getElementById('tab'); var tHead = oTab.tHead; var tCells = tHead.rows[0].cells; var tBody = oTab.tBodies[0]; var aRows = tBody.rows; var data = null; getData(); function getData() { var xml = new XMLHttpRequest; xml.open('get', 'data.txt', false); xml.onreadystatechange = function () { if (xml.readyState === 4 && /^2\d{2}$/.test(xml.status)) { data = utils.jsonParse(xml.responseText); } }; xml.send(); } bind(); function bind() { var str = ''; for (var i = 0; i < data.length; i++) { var curData = data[i]; curData.sex = curData.sex == 0 ? '男' : '女'; str += '<tr>\ <td>' + curData.name + '</td>\ <td>' + curData.age + '</td>\ <td>' + curData.score + '</td>\ <td>' + curData.sex + '</td>\ </tr>'; } tBody.innerHTML = str; } changeColor(); function changeColor() { for (var i = 0; i < aRows.length; i++) { aRows[i].className = 'bg' + i % 2; } } function sort(n) { for (var i = 0; i < tCells.length; i++) { tCells[i].flag = i == n ? tCells[i].flag * -1 : -1; } var ary = utils.makeArray(aRows); ary.sort(function (a, b) { a = a.cells[n].innerHTML; b = b.cells[n].innerHTML; if (isNaN(a) && isNaN(b)) { return a.localeCompare(b) * tCells[n].flag; } return (a - b) * tCells[n].flag; }); var frg = document.createDocumentFragment(); for (var i = 0; i < ary.length; i++) { frg.appendChild(ary[i]); } tBody.appendChild(frg); frg = null; changeColor(); } for (var i = 0; i < tCells.length; i++) { if (tCells[i].className == 'cursor') { tCells[i].flag = -1; tCells[i].index = i; tCells[i].onclick = function () { sort(this.index); } } } })();
感謝各位的閱讀!關于“JS如何實現隔行換色的表格排序”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。