search
HomeWeb Front-endJS TutorialSummary of common operations methods for JavaScript tables_javascript skills

The examples in this article summarize common operation methods of JavaScript tables. Share it with everyone for your reference. The details are as follows:

<!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>
<title>无标题页</title>
<script type="text/javascript">
var mytable=null;
window.onload=function(){
mytable=new CTable("tbl",10); //随机创建10行表格
}
Array.prototype.each=function(f){ //数组的遍历
for(var i=0;i<this.length;i++) f(this[i],i,this)}
function $A(arrayLike){ //数值的填充
for(var i=0,ret=[];i<arrayLike.length;i++) ret.push(arrayLike[i]);
return ret
}
Function.prototype.bind = function() { //数据的绑定
 var __method = this, args = $A(arguments), object = args.shift();
 return function() {
  return __method.apply(object, args.concat($A(arguments)));
 }
}
function CTable(id,rows){
this.tbl=typeof(id)=="string"&#63;document.getElementById(id):id;
if (rows && /^d+$/.test(rows)) this.addrows(rows) //为表格添加行数
}
CTable.prototype={
addrows:function(n){ //随机添加n行
new Array(n).each(this.add.bind(this))
},
add:function(){ //添加1行
var self=this;
var tr = self.tbl.insertRow(-1),td1= tr.insertCell(-1),td2= tr.insertCell(-1),td3= tr.insertCell(-1);
var chkbox=document.createElement("INPUT")
chkbox.type="checkbox"
chkbox.onclick=self.highlight.bind(self)
td1.appendChild(chkbox) //第一列添加复选框
td1.setAttribute("width","35")
td2.innerHTML=Math.ceil(Math.random()*99) //第二列的随机填充值
td3.innerHTML=Math.ceil(Math.random()*99) //第三列的随机填充值
},
del:function(){ //删除所选行
var self=this
$A(self.tbl.rows).each(function(tr){if (self.getChkBox(tr).checked) tr.parentNode.removeChild(tr)})
},
up:function(){ //上移所选行
  var self=this
  var upOne=function(tr){ //上移1行
  if (tr.rowIndex>0){
  self.swapTr(tr,self.tbl.rows[tr.rowIndex-1])
  self.getChkBox(tr).checked=true}}
  var arr=$A(self.tbl.rows).reverse() //反选
  if (arr.length>0 && self.getChkBox(arr[arr.length-1]).checked){
  for(var i=arr.length-1;i>=0;i--){
  if (self.getChkBox(arr[i]).checked){
  arr.pop()     
  }else{
  break}}}
  arr.reverse().each(function(tr){if (self.getChkBox(tr).checked) upOne(tr)});
},
down:function(){ //下移所选行
  var self=this
  var downOne=function(tr){   
  if (tr.rowIndex<self.tbl.rows.length-1) {
  self.swapTr(tr,self.tbl.rows[tr.rowIndex+1]);
  self.getChkBox(tr).checked=true;
  }}
  var arr=$A(self.tbl.rows)
  if (arr.length>0 && self.getChkBox(arr[arr.length-1]).checked){
  for(var i=arr.length-1;i>=0;i--){
  if (self.getChkBox(arr[i]).checked){
  arr.pop()
  }else{
  break}}
  }
  arr.reverse().each(function(tr){if (self.getChkBox(tr).checked) downOne(tr)});
},
sort:function(){ //排序 
var self=this,order=arguments[0];
var sortBy=function(a,b){
if (typeof(order)=="number"){ //数字,则按数字指示的列排序
return Number(a.cells[order].innerHTML)>=Number(b.cells[order].innerHTML)&#63;1:-1; 
//转化为数字类型比较大小
}else if (typeof(order)=="function"){
//返回结果排序
return order(a,b);
}else{
return 1;
}
}
$A(self.tbl.rows).sort(sortBy).each(function(x){
var checkStatus=self.getChkBox(x).checked;
self.tbl.firstChild.appendChild(x);
if (checkStatus) self.getChkBox(x).checked=checkStatus;
});
},
rnd:function(){ //随即选择几行数据
var self=this,selmax=0,tbl=self.tbl;
if (tbl.rows.length){
 selmax=Math.max(Math.ceil(tbl.rows.length/4),1);
//选择的行数不超过tr数的1/4
 $A(tbl.rows).each(function(x){
self.getChkBox(x).checked=false;
self.restoreBgColor(x)
})
}else{
return alert("无数据可以选")
}
new Array(selmax).each(function(){
var tr=tbl.rows[Math.floor(Math.random()*tbl.rows.length)]
self.getChkBox(tr).checked=true;
self.highlight({target:self.getChkBox(tr)})
})
},
highlight:function(){ //设置行的背景色
var self=this;
var evt=arguments[0] || window.event
var chkbox=evt.srcElement || evt.target
var tr=chkbox.parentNode.parentNode
chkbox.checked&#63;self.setBgColor(tr):self.restoreBgColor(tr)
},
swapTr:function(tr1,tr2){ //交换tr1和tr2的位置
var target=(tr1.rowIndex<tr2.rowIndex)&#63;tr2.nextSibling:tr2;
var tBody=tr1.parentNode
tBody.replaceChild(tr2,tr1);
  tBody.insertBefore(tr1,target);
},
getChkBox:function(tr){ //从tr得到 checkbox对象
return tr.cells[0].firstChild
},
restoreBgColor:function(tr){     
tr.style.backgroundColor="#ffffff"
},
setBgColor:function(tr){ //设置背景色
tr.style.backgroundColor="#c0c0c0"
}
}
function f(a,b){
var sumRow=function(row){
return Number(row.cells[1].innerHTML)+Number(row.cells[2].innerHTML)
};
return sumRow(a)>sumRow(b)&#63;1:-1;
}
</script>
</head>
<body>
<button onClick="javascript:mytable.rnd()">随机选择行</button>
<button onClick="javascript:mytable.add()">添加一行</button>
<button onClick="javascript:mytable.del()">删除选定行</button>
<button onClick="javascript:mytable.up()">上移选定行</button>
<button onClick="javascript:mytable.down()">下移选定行</button>
<button onClick="javascript:mytable.sort(1)">按第一列排序</button>
<button onClick="javascript:mytable.sort(f)">按数据和排序</button>
<br/><br/>
<table width=100%>
<tr>
<td valign="top"><table border id="tbl" width="80%"></table></td>
</tr>
</table>
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),