可编辑的table(原生JS+jQuery)

那年仲夏 提交于 2020-03-24 21:45:10

 

 

原生js:

 

<!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>Table</title> 
<style type="text/css"> 
body{ font-size:12px} 
#tab{ border-collapse: collapse;} 
.edit{ height:16px; width:98%; background-color:#EFF7FF; font-size:12px; border:0px;} 
#tab thead td{ background:url(/upload/201005/20100531233452190.bmp);color:#183C94} 
#tab tbody td{ overflow:hidden} 
#tab td{border: 1px solid #CECFCE;height:20px;line-height:20px;vertical-align:middle; } 
#tab td.tc{text-align:center;} 
.cc{width:10px;height:6px; border:1px solid #999999; background-color:#FFFFFF; position:absolute; display:none;} 
#tab td.red{border-color:#f30;} 
.ww{height:100%;width:1px;background:#CECFCE;float:right;margin-right:-1px;cursor:sw-resize} 

.line{ width:2px; background-color:#999999; position:absolute; display:none} 
</style> 
</head> 
<body> 
<table id="tab" border="0" cellspacing="1" cellpadding="0"> 
<thead> 
<tr> 
<td width="60"class="tc" ><span>ID</span><div class="ww"></div></td> 
<td width="60"class="tc"><span>选中</span><div class="ww"></div></td> 
<td width="100" class="tc"><span>姓名</span><div class="ww"></div></td> 
<td width="100" class="tc" ><span>生日</span><div class="ww"></div></td> 
<td width="180" class="tc" ><span>备注</span><div class="ww"></div></td> 
</tr> 
</thead> 
<tbody> 
<tr> 
<td height="16">1</td> 
<td><input type ="checkbox"></td> 
<td>张三</td> 
<td>1982-05-27</td> 
<td>杯具,全是杯具</td> 
</tr> 
<tr> 
<td>3</td> 
<td><input type ="checkbox"></td> 
<td>李四</td> 
<td>1983-06-27</td> 
<td>恩恩我魔兽技术不错</td> 
</tr> 
<tr> 
<td>2</td> 
<td><input type ="checkbox"></td> 
<td>王五</td> 
<td>1983-05-27</td> 
<td>波斯王子 时之刃还不错</td> 
</tr> 
<tr> 
<td>4</td> 
<td><input type ="checkbox"></td> 
<td>赵六</td> 
<td>1983-05-27</td> 
<td>我叫赵六</td> 
</tr> 
<tr> 
<td>5</td> 
<td><input type ="checkbox"></td> 
<td>朱八</td> 
<td>1986-05-27</td> 
<td>洗洗睡吧</td> 
</tr> 
</tbody> 
</table> 
<script language="javascript"> 
var Sys = (function(ua){ 
var s = {}; 
s.IE = ua.match(/msie ([\d.]+)/)?true:false; 
s.Firefox = ua.match(/firefox\/([\d.]+)/)?true:false; 
s.Chrome = ua.match(/chrome\/([\d.]+)/)?true:false; 
s.IE6 = (s.IE&&([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6))?true:false; 
s.IE7 = (s.IE&&([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 7))?true:false; 
s.IE8 = (s.IE&&([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 8))?true:false; 
return s; 
})(navigator.userAgent.toLowerCase()); 
function $(Id){ 
return document.getElementById(Id); 
}; 
function addListener(element,e,fn){ 
element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn); 
}; 
function removeListener(element,e,fn){ 
element.removeEventListener?element.removeEventListener(e,fn,false):element.detachEvent("on" + e,fn); 
}; 
var Css = function(e,o){ 
if(typeof o=="string") 
{ 
e.style.cssText=o; 
return; 
} 
for(var i in o) 
e.style[i] = o[i]; 
}; 
var Bind = function(object, fun) { 
var args = Array.prototype.slice.call(arguments).slice(2); 
return function() { 
return fun.apply(object, args); 
}; 
}; 
var BindAsEventListener = function(object, fun) { 
var args = Array.prototype.slice.call(arguments).slice(2); 
return function(event) { 
return fun.apply(object, [event || window.event].concat(args)); 
}; 
}; 
var Extend = function(destination, source){ 
for (var property in source) { 
destination[property] = source[property]; 
}; 
}; 
var Class = function(properties){ 
var _class = function(){return (arguments[0] !== null && this.initialize && typeof(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;}; 
_class.prototype = properties; 
return _class; 
}; 
var Table = new Class({ 
initialize : function(tab,set){ 
this.table = tab; 
this.thead = tab.getElementsByTagName('thead')[0]; //常用的dom元素做成索引 
this.theadtds = this.thead.getElementsByTagName('td'); // 
this.rows = []; //里面tbodys记录所有tr的引用 这里用数组记录是因为数组有reverse方法,可以用来正序,反序 
this.clos = {}; //里面记录所有列元素的引用 
this.edits = {}; //编辑表格的规则和提示 
this.sortCol = null; //记录哪列正在排序中 
this.inputtd = null; //记录哪个input被编辑了 
this.closarg ={ 
tdnum : null, 
totdnum : null, 
closmove : BindAsEventListener(this,this.closmove), 
closup : BindAsEventListener(this,this.closup) 
};//关于列拖拽的一些属性方法 
this.widtharg ={ 
td : null, 
nexttd : null, 
x : 0, 
tdwidth : 0, 
nexttdwidth : 0, 
widthmove : BindAsEventListener(this,this.widthmove), 
widthup : BindAsEventListener(this,this.widthup) 
}; 
var i=0,j=0,d=document,rows =tab.tBodies[0].rows,tds1 = tab.tBodies[0].getElementsByTagName('td'),edit=[]; 
var divs = this.thead.getElementsByTagName('div'); 
this.input = d.createElement('input'); //编辑用的input 
this.input.type = "text"; 
this.input.className = 'edit'; 
this.img = d.body.appendChild(d.createElement('div')); 
this.img.className ="cc" ; 
this.line = d.body.appendChild(d.createElement('div')); 
this.line.className = 'line'; 
this.line.style.top = tab.offsetTop +"px"; 
if(Sys.IE6){ 
this.checkbox = {}; //记录那些checkbox被选中了 处理ie6不兼容的问题 
var checkboxs = tab.getElementsByTagName('input'),k =0; 
for(var lll=checkboxs.length;k<lll;k++) 
checkboxs[k].type=="checkbox"&&addListener(checkboxs[k],"click",Bind(this,function(elm,k){ 
elm.checked==true?(this.checkbox[k] = elm):(delete this.checkbox[k]); 
},checkboxs[k],k)); 
}; 
for(var l=set.length;i<l;i++){ 
addListener(this.theadtds[set[i].id],'click',Bind(this,this.sortTable,this.theadtds[set[i].id],set[i].id,set[i].type)); 
set[i].edit&&(this.edits[set[i].id]={rule:set[i].edit.rule,message:set[i].edit.message}); 
}; 
for(l=rows.length;j<l;j++) 
this.rows[j]=rows[j]; 
for(var k=0,l=this.theadtds.length;k<l;k++){ 
this.clos[k]=[]; 
this.theadtds[k].setAttribute('clos',k) 
addListener(this.theadtds[k],'mousedown',BindAsEventListener(this,this.closdrag)); 
} 
for(var i=0,l=tds1.length;i<l;i++){ 
var p = i<this.theadtds.length-1?i:i%this.theadtds.length; 
this.clos[p][this.clos[p].length] = tds1[i]; 
this.edits[p]&&tds1[i].setAttribute('edit',p); 
} 
for(var i=0,l=divs.length;i<l;i++){ 
addListener(divs[i],'mousedown',BindAsEventListener(this,this.widthdrag)); 
} 
/*---------------------------------------------*/ 
/*---------------------------------------------*/ 
addListener(this.thead,'mouseover',BindAsEventListener(this,this.theadhover)); 
addListener(tab.tBodies[0],'dblclick',BindAsEventListener(this,this.edit)); 
addListener(this.input,'blur',Bind(this,this.save,this.input)); 
}, 
theadhover : function(e){ 
e = e || window.event; 
var obj = e.srcElement ||e.target; 
if(obj.nodeName.toLowerCase() =='td') 
this.closarg.totdnum = (obj).getAttribute('clos'); 
else if(obj.nodeName.toLowerCase() =='div') 
obj.style.cursor="sw-resize"; 
}, 
widthdrag : function(e){ 
if(Sys.IE){e.cancelBubble=true}else{e.stopPropagation()} 
this.widtharg.x = e.clientX; 
this.widtharg.td = (e.srcElement ||e.target).parentNode; 
if(Sys.IE){ 
this.widtharg.nexttd = this.widtharg.td.nextSibling; 
}else{ 
this.widtharg.nexttd = this.widtharg.td.nextSibling.nextSibling; 
} 
this.widtharg.tdwidth = this.widtharg.td.offsetWidth; 
this.widtharg.nexttdwidth = this.widtharg.nexttd.offsetWidth; 
this.line.style.height = this.table.offsetHeight +"px"; 
addListener(document,'mousemove',this.widtharg.widthmove); 
addListener(document,'mouseup',this.widtharg.widthup); 
}, 
widthmove : function(e){ 
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); 
var x = e.clientX - this.widtharg.x,left = e.clientX,clientx=e.clientX ; 
if(clientx<this.widtharg.x){ 
if(this.widtharg.x - clientx>this.widtharg.tdwidth-35) 
left = this.widtharg.x - this.widtharg.tdwidth+35; 
} 
if(clientx>this.widtharg.x) 
{ 
if(clientx - this.widtharg.x>this.widtharg.nexttdwidth-35) 
left = this.widtharg.x + this.widtharg.nexttdwidth-35; 
} 
Css(this.line,{display:"block",left:left+"px"}); 

}, 
widthup : function(e){ 
this.line.style.display = "none"; 
var x= parseInt(this.line.style.left) - this.widtharg.x; 
this.widtharg.nexttd.style.width = this.widtharg.nexttdwidth -x +'px'; 
this.widtharg.td.style.width = this.widtharg.tdwidth + x +'px'; 
removeListener(document,'mousemove',this.widtharg.widthmove); 
removeListener(document,'mouseup',this.widtharg.widthup); 
}, 
closdrag : function(e){ 
e = e || window.event; 
var obj = e.srcElement ||e.target; 
if(obj.nodeName.toLowerCase()=="span")obj =obj.parentNode; 
this.closarg.tdnum = obj.getAttribute('clos');; 
addListener(document,'mousemove',this.closarg.closmove); 
addListener(document,'mouseup',this.closarg.closup); 
}, 
closmove : function(e){ 
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); 
Css(this.img,{display:"block",left:e.clientX+9+"px",top:e.clientY+20+"px"}); 
}, 
closup : function(){ 
this.img.style.display = "none"; 
removeListener(document,'mousemove',this.closarg.closmove); 
removeListener(document,'mouseup',this.closarg.closup); 
if(this.closarg.totdnum==this.closarg.tdnum)return; 
var rows =this.table.getElementsByTagName('tr'),tds,n,o; 
if((parseInt(this.closarg.tdnum)+1)==parseInt(this.closarg.totdnum)) 
{ 
o = this.closarg.tdnum; 
n = this.closarg.totdnum; 
} 
else 
{ 
n = this.closarg.tdnum; 
o = this.closarg.totdnum; 
} 
for(var i=0,l=rows.length;i<l;i++) 
{ 
tds = rows[i].getElementsByTagName('td'); 
try{ 
rows[i].insertBefore(tds[n],tds[o]); 
} 
catch(err){ 
return; 
} 
} 
for(var i=0,l=this.theadtds.length;i<l;i++) 
this.theadtds[i].setAttribute('clos',i); 
}, 
edit: function(e){ 
var o = e.srcElement || e.target; 
if(!o.getAttribute('edit'))return; 
this.inputtd = o; 
var v = o.innerHTML; 
o.innerHTML = ""; 
o.appendChild(this.input); 
this.input.value=v; 
this.input.focus(); 
}, 
save : function(o){ 
var edit=this.edits[o.parentNode.getAttribute('edit')]; 
if(edit.rule.test(this.input.value)){ 
this.inputtd.innerHTML = this.input.value; 
this.inputtd=null; 
}else{ 
alert(edit.message); 
} 
}, 
sortTable :function(td,n,type){ 
var frag=document.createDocumentFragment(),str= td.getElementsByTagName('span')[0].innerHTML,span=td.getElementsByTagName('span')[0]; 
if(this.row!=null||td==this.sortCol){ 
this.rows.reverse(); 
span.innerHTML =str.replace(/.$/,str.charAt(str.length-1)=="↓"?"↑":"↓") ; 
}else{ 
this.rows.sort(this.compare(n,type)); 
span.innerHTML = span.innerHTML + "↑"; 
this.sortCol!=null&&(this.sortCol.getElementsByTagName('span')[0].innerHTML = this.sortCol.getElementsByTagName('span')[0].innerHTML.replace(/.$/,'')); 
}; 
for(var i=0,l=this.rows.length;i<l;i++) 
frag.appendChild(this.rows[i]); 
this.table.tBodies[0].appendChild(frag); 
if(Sys.IE6){ 
for(var s in this.checkbox) 
this.checkbox[s].checked = true; 
} 
this.sortCol = td; 
}, 
compare :function(n,type){ 
return function (a1,a2){ 
var convert ={ 
int : function(v){return parseInt(v)}, 
float : function(v){return parseFloat(v)}, 
date : function(v){return v.toString()}, 
string : function(v){return v.toString()} 
}; 
!convert[type]&&(convert[type]=function(v){return v.toString()}); 
a1 =convert[type](a1.cells[n].innerHTML); 
a2 =convert[type](a2.cells[n].innerHTML); 
if(a1==a2)return 0; 
return a1<a2?-1:1; 
}; 
} 
}); 
window.onload = function(){ 
var set = [ 
{id:0,type:"int"}, 
{id:2,type:"string",edit:{rule:/^([a-z]|[\u4e00-\u9fa5]){2,}$/i,message:"请输入2位以上的汉字,或者是字母"}}, 
{id:3,type:"date",edit:{rule:/^\d{4}\-\d{2}\-\d{2}$/,message:"按这中格式输入日期1985-02-30"}}, 
{id:4,type:"string",edit:{rule:/^.{4,10}$/,message:"请输入4到10个字符"}} 
]; 
new Table($("tab"),set); 
} 
</script> 
</body> 
</html> 

  

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>Untitled Document</title>
<style type="text/css">
<!--
input {
 font-family: Geneva, Arial, Helvetica, sans-serif;
 font-size: 12px;
 color: #999999;
 background-color: #FFFFE1;
 border: 1px solid #999999;
}
-->
</style>
</head>
<body>
<div id="aa"></div>
<table width="80%" id="tab1"  border="1" bordercolorlight="#CCCCCC" bordercolordark="#FFFFFF" onclick="setEdit(event.srcElement)">
  <tr>
    <td width="20%" id="td1">a</td>
    <td width="20%">bb</td>
    <td width="20%">asdf</td>
    <td width="20%">eee</td>
    <td width="20%">adsf</td>
  </tr>
  <tr>
    <td>1</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>9</td>
  </tr>
  <tr>
    <td>as</td>
    <td>asdfsdfa</td>
    <td>sadfsdaf</td>
    <td>sadfsdfa</td>
    <td>sdafsadf</td>
  </tr>
  <tr>
    <td>sadfsdfa</td>
    <td>asdf</td>
    <td>&nbsp;</td>
    <td>asdfasdf</td>
    <td>asdfasf</td>
  </tr>
  <tr>
    <td>asdfsadf</td>
    <td>asdfsadf</td>
    <td>asdfasdfasd</td>
    <td>ea</td>
    <td>asdfasfd</td>
  </tr>
</table>
</body>
</html>
<script>
oldObj="";
var newNode=document.createElement("input");
newNode.type="text";
function setEdit(click_td){
 var obj;
 
 if(click_td.tagName=="TD"){
  if(oldObj!=""){
   oldObj.removeChild(eval("tmpText"));
   if(newNode.vlaue=="") oldObj.innerText="&nbsp;";
   else oldObj.innerText=newNode.value;
  }
  
  obj=click_td;
  oldObj=obj;
  //newNode.width=obj.clientWidth;
  //newNode.height=obj.clientHeight;
  newNode.width=obj.offsetWidth;
  newNode.height=obj.offsetHeight;
  newNode.id="tmpText";
  newNode.value=obj.innerText;
  obj.innerText="";
  obj.appendChild(newNode);
  newNode.focus();
 }
}
</script>

 

 

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>新建网页 1</title>
</head>
<script language=javascript>
var disinput=0;
function presskey(obj2,obj1)
{
    if (event.keyCode==13) noneinput(obj2,obj1);
}
function put1(fcolor,bcolor,isb)
{
        var writeb='';
        if (isb==1) writeb='font-weight: bold;';
        document.write('<table border="0" cellpadding="0" bgcolor="'+bcolor+'" style="border-collapse: collapse" width="100%" height="100%" bordercolor="#7777777" id="table2">')
        for (i = 1; i < 97; i++) 
        {
            document.write('<tr><td style="'+writeb+'color:'+fcolor+';border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px;height: 22px" class=es2 align="center" onclick="showinput(this);">'+i+'</td></tr>')
           }
        document.write('</table>')
}
function showinput(obj1)
{
if (disinput==0)
    {
    var tdval=obj1.innerText;
    obj1.innerHTML='';
    obj1.innerHTML='<input type="text" name="T1" id="T1" size="20" style="width=100%;height=100%" class=es2 onblur="noneinput(this,this.parentElement)" onkeydown="return presskey(this,this.parentElement)">';
    document.all.T1.value=tdval;
    document.all.T1.select();
    document.all.T1.focus();

    disinput=1;
    }
}

function noneinput(obj2,obj1)
{
    if (disinput==1)
    {
        var tdval=obj2.value;
        obj1.innerHTML='';
        obj1.innerText=tdval;
        disinput=0;
    }
}

function showtextarea(obj1,fcolor,bcolor,isb)
{
if (disinput==0)
    {
    var tdval=obj1.innerText;
    obj1.innerHTML='';
    obj1.innerHTML='<textarea rows="96" name="S1" id="S1" cols="6" class=es2 style="padding:0;padding-left:10px; border-width:0px;line-height: 22px;height=100%;background-color=#000000;color:#FFFFFF" onblur="nonetextarea(this.parentElement,\''+fcolor+'\',\''+bcolor+'\','+isb+')"></textarea>';
    document.all.S1.value=tdval;
    document.all.S1.select();
    document.all.S1.focus();

    disinput=1;
    }
}
function nonetextarea(obj1,fcolor,bcolor,isb)
{
if (disinput==1)
    {
    var tdval=obj1.innerText;
    var tdarray,tdstring;
    var writeb='';
    if (isb==1) writeb='font-weight: bold;';
    //var bcolor='#ffffff',writeb='',fcolor='#000000';
    obj1.innerHTML='';
    tdarray=tdval.split('\r');
    tdval='';
    tdval='<table border="0" cellpadding="0" bgcolor="'+bcolor+'" style="border-collapse: collapse" width="100%" height="100%" bordercolor="#7777777" id="table2">';
    for (tdstring in tdarray)
    {tdval=tdval+'<tr><td style="'+writeb+'color:'+fcolor+';border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px;height: 22px" class=es2 align="center" onclick="showinput(this);">'+tdarray[tdstring]+'</td></tr>'}
    tdval=tdval+'</table>'
    obj1.innerHTML=tdval;
    disinput=0;
    }
}
</script>

<style type="text/css"><!--

td,body {  font-size: 9pt}

a:link{ color:#000000; text-decoration:none}     

a:visited{COLOR: #000000; TEXT-DECORATION: none} 

a:active{color:green;text-decoration:none}

a:hover{color:red;text-decoration:underline} 

.es1          { font-family: Tahoma; font-size: 8pt; color: #ffffff }
.es2          { font-family: Tahoma; font-size: 8pt; color: #000000}
.es3          { font-family: Tahoma; font-size: 8pt; color: #ff0000 }
.es4          { font-family: Tahoma; font-size: 8pt; color: #00ff00 }
.es5          { font-family: Tahoma; font-size: 8pt; color: #ff5522 }

.es6          { font-size: 8pt; font-family: Tahoma; color: #ffffff }
.es7          { font-size: 8pt; font-family: Tahoma; color: #ffff00 }
.es8          { font-size: 9pt; font-family: 宋体; color: #ff0000 }
.es9          { font-size: 9pt; font-family: 宋体; color: #538bff }
--> 

</style>
<body>
<div align=center>
<table border="1" cellpadding="0" style="border-collapse: collapse" width="783" height="100%" bordercolor="#777777" id="table1">
    <form method="POST" action="_derived/nortbots.htm" onSubmit="location.href='_derived/nortbots.htm';return false;" webbot-onSubmit webbot-action="--WEBBOT-SELF--">
    <tr>
        <td width="4%" align="center" height="21" onclick="showinput();">序号</td>
        <td width="10%" align="center" height="21" colspan="2">第1段</td>
        <td width="10%" align="center" height="21" colspan="2">第2段</td>
        <td width="10%" align="center" height="21" colspan="2">第3段</td>
        <td width="10%" align="center" height="21" colspan="2">第4段</td>
        <td width="10%" align="center" height="21" colspan="2">第5段</td>
        <td width="9%" align="center" height="21" colspan="2">第6段</td>
        <td width="9%" align="center" height="21" colspan="2">第7段</td>
        <td width="9%" align="center" height="21" colspan="2">第8段</td>
        <td width="9%" align="center" height="21" colspan="2">第9段</td>
        <td width="10%" align="center" height="21" colspan="2">第10段</td>
    </tr>
    <tr>
        <td width="5%" align="center" height="21">12</td>
        <td width="5%" align="center" height="21" onclick="showtextarea(document.all.td1_1,'#ff0000','#dddddd',0);">列头</td>
        <td width="5%" align="center" height="21">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21">列头</td>
        <td width="4%" align="center" height="21">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="4%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="4%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="4%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
        <td width="5%" align="center" height="21" style="font-size: 9pt">列头</td>
    </tr>
    <tr valign=top>
        <td align="center">
        <script language=javascript>
        put1('#484848','#ffffff',1);
        </script>
        </td>
        <td align="center" id="td1_1" valign="top">
        <script language=javascript>
        put1('#ff0000','#dddddd',0);
        </script>
        </td>
        <td align="center">  </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
        <td align="center"> </td>
    </tr>
    <tr>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
    </tr>
    </form>
</table>
</div>
</body>

</html>

 

 

 

 

 

 

jQuery版本:

 

 

 

<!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=utf-8" />
<title>jquery表格可编辑修改表格里面的数值</title>
<style type="text/css">
/* page styles */
* { margin:0; padding:0; }
body{font-family:"Segoe UI", Frutiger,Tahoma,Helvetica,"Helvetica Neue", Arial, sans-serif;font-size:62.5%;}
/*demo styles*/
table{width:900px; margin:0 auto;border-collapse:collapse; }
td, th{ width:10%; font-size:14px; padding:10px 0; text-align:center;border:1px solid #ddd; }
th {background-color:#f4f4f4;} 
/* input */
td.input{ position:relative; }
td input{ width:100%; border:1px solid #CF5C74; background:#E8C1D8; border-radius:4px; display:block; position:absolute; text-align:center; font-size:14px; left:0; top:0; padding:11px 0; margin:-1px 0 0 -1px; }
td.hover{background:#eee;}
</style>
</head>
<body>

    <table border="0" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <td></td>
                <th scope="col">food</th>
                <th scope="col">auto</th>
                <th scope="col">household</th>
                <th scope="col">furniture</th>
                <th scope="col">kitchen</th>
                <th scope="col">bath</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th scope="row">Mary</th>
                <td>190</td>
                <td>160</td>
                <td>40</td>
                <td>120</td>
                <td>30</td>
                <td>70</td>
            </tr>
            <tr>
                <th scope="row">Tom</th>
                <td>3</td>
                <td>40</td>
                <td>30</td>
                <td>45</td>
                <td>35</td>
                <td>49</td>
            </tr>
            <tr>
                <th scope="row">Brad</th>
                <td>10</td>
                <td>180</td>
                <td>10</td>
                <td>85</td>
                <td>25</td>
                <td>79</td>
            </tr>
            <tr>
                <th scope="row">Kate</th>
                <td>40</td>
                <td>80</td>
                <td>90</td>
                <td>25</td>
                <td>15</td>
                <td>119</td>
            </tr>        
        </tbody>
    </table>    


<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){    

    $('table td').click(function(){
        if(!$(this).is('.input')){
            $(this).addClass('input').html('<input type="text" value="'+ $(this).text() +'" />').find('input').focus().blur(function(){
                $(this).parent().removeClass('input').html($(this).val() || 0);
            });                    
        }
    }).hover(function(){
        $(this).addClass('hover');
    },function(){
        $(this).removeClass('hover');
    });

});
</script>
</body>
</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=utf-8" />
<title>jQuery的跨浏览器可编辑表格</title>
<style type="text/css">
body{
    font-size: 14px;
}
table{
    color: #4F6B72; 
    border: 1px solid #C1DAD7;
    border-collapse: collapse;
    width: 400px;
}

th{
    width: 50%;
    border: 1px solid #C1DAD7;
}
td{
    width: 50%;
    border: 1px solid #C1DAD7;
}
/*Code2*/


a{
    color: #C75F3E;
}
</style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th colspan="2">鼠标点击表格就可以编辑</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>学号</th>
                <th>姓名</th>
            </tr>
            <tr>
                <td>000001</td>
                <td>张三</td>
            </tr>
            <tr>
                <td>000002</td>
                <td>李四</td>
            </tr>
            <tr>
                <td>000003</td>
                <td>王五</td>
            </tr>
            <tr>
                <td>000004</td>
                <td>赵六</td>
            </tr>
        </tbody>
    </table>
    
    
    
    
    
    
    
    
    
    
    






<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>

<script type="text/javascript">
// JavaScript Document
/**Code3**/
/*
$(document).ready(function(){
    //找到学号这一列的所有单元格
    //因为学号这一列的单元格在所有td中的位置是偶数(0,2,4,6),所以通过even就可以筛选到td中偶数位的单元格
    var numTd = $("tbody  td:even");
    
    //单击这些td时,创建文本框
    numTd.click(function(){
        //创建文本框对象
        var inputobj = $("<input type='text'>");
        //获取当前点击的单元格对象
        var tdobj = $(this);
        
        //去除文本框的border
        inputobj.css("border","0");
        //让文本框和单元格的宽度保持一致
        inputobj.width(tdobj.width());
        //让文本框的字体和单元格的字体大小一样
        inputobj.css("font-size",tdobj.css("font-size"));
        //让文本框和单元格的字体保持一致
        inputobj.css("font-family",tdobj.css("font-family"));
        //让文本框和单元格的背景保持一致
        inputobj.css("background-color",tdobj.css("background-color"));
        
        //appendTo方法把文本框添加到td中
        inputobj.appendTo(tdobj);
    });
});
*/
/**Code3**/

/**Code4**/
/*
$(document).ready(function(){
    //找到学号这一列的所有单元格
    //因为学号这一列的单元格在所有td中的位置是偶数(0,2,4,6),所以通过even就可以筛选到td中偶数位的单元格
    var numTd = $("tbody  td:even");
    
    //单击这些td时,创建文本框
    numTd.click(function(){
        //创建文本框对象
        var inputobj = $("<input type='text'>");
        //获取当前点击的单元格对象
        var tdobj = $(this);
        //获取单元格中的文本
        var text = tdobj.html();
        
        //清空单元格的文本
        tdobj.html("");
        
        //去除文本框的border
        inputobj.css("border","0");
        //让文本框和单元格的宽度保持一致
        inputobj.width(tdobj.width());
        //让文本框的字体和单元格的字体大小一样
        inputobj.css("font-size",tdobj.css("font-size"));
        //让文本框和单元格的字体保持一致
        inputobj.css("font-family",tdobj.css("font-family"));
        //让文本框和单元格的背景保持一致
        inputobj.css("background-color",tdobj.css("background-color"));
        inputobj.css("color","#C75F3E");
        
        //给文本框赋值
        inputobj.val(text);
        
        //appendTo方法把文本框添加到td中
        inputobj.appendTo(tdobj);
    });
});
*/
/**Code4**/

/**Code5**/
/*
$(document).ready(function(){
    //找到学号这一列的所有单元格
    //因为学号这一列的单元格在所有td中的位置是偶数(0,2,4,6),所以通过even就可以筛选到td中偶数位的单元格
    var numTd = $("tbody  td:even");
    
    //单击这些td时,创建文本框
    numTd.click(function(){
        //创建文本框对象
        var inputobj = $("<input type='text'>");
        //获取当前点击的单元格对象
        var tdobj = $(this);
        //获取单元格中的文本
        var text = tdobj.html();
        
        //清空单元格的文本
        tdobj.html("");
        
        inputobj.css("border","0")
                .css("font-size",tdobj.css("font-size"))
                .css("font-family",tdobj.css("font-family"))
                .css("background-color",tdobj.css("background-color"))
                .css("color","#C75F3E")
                .width(tdobj.width())
                .val(text)
                .appendTo(tdobj);
        
        inputobj.click(function(){
            return false;
        });
    });
});
*/
/**Code5**/

/**Code6**/
/*
inputobj.click(function(){
            return false;
        });
*/
/**Code6**/

/**Code7**/
/*
$(document).ready(function(){
    //找到学号这一列的所有单元格
    //因为学号这一列的单元格在所有td中的位置是偶数(0,2,4,6),所以通过even就可以筛选到td中偶数位的单元格
    var numTd = $("tbody  td:even");
    
    //单击这些td时,创建文本框
    numTd.click(function(){
        //创建文本框对象
        var inputobj = $("<input type='text'>");
        //获取当前点击的单元格对象
        var tdobj = $(this);
        //获取单元格中的文本
        var text = tdobj.html();
        
        //如果当前单元格中有文本框,就直接跳出方法
        //注意:一定要在插入文本框前进行判断
        if(tdobj.children("input").length>0){
            return false;
        }
        //清空单元格的文本
        tdobj.html("");
        
        inputobj.css("border","0")
                .css("font-size",tdobj.css("font-size"))
                .css("font-family",tdobj.css("font-family"))
                .css("background-color",tdobj.css("background-color"))
                .css("color","#C75F3E")
                .width(tdobj.width())
                .val(text)
                .appendTo(tdobj);
                
        inputobj.get(0).select();
        //阻止文本框的点击事件
        inputobj.click(function(){
            return false;
        });
        
        
    });
});
*/
/**Code7**/


/**Code10**/
/*
        //处理文本框上回车和esc按键的操作
        //jQuery中某个事件方法的function可以定义一个event参数,jQuery会屏蔽浏览器的差异,传递给我们一个可用的event对象
        inputobj.keyup(function(event){
            //获取当前按键的键值
            //jQuery的event对象上有一个which的属性可以获得键盘按键的键值
            var keycode = event.which;
            //处理回车的情况
            if(keycode==13){
                //获取当前文本框的内容
                var inputtext = $(this).val();
                //将td的内容修改成文本框中的内容
                tdobj.html(inputtext);
            }
            //处理esc的情况
            if(keycode == 27){
                //将td中的内容还原成text
                tdobj.html(text);
            }
        });
*/
/**Code10**/

/**Code11**/
$(document).ready(function(){
    //找到学号这一列的所有单元格
    //因为学号这一列的单元格在所有td中的位置是偶数(0,2,4,6),所以通过even就可以筛选到td中偶数位的单元格
    //var numTd = $("tbody  td:even");
    var numTd = $("tbody  td");
    
    //单击这些td时,创建文本框
    numTd.click(function(){
        //创建文本框对象
        var inputobj = $("<input type='text'>");
        //获取当前点击的单元格对象
        var tdobj = $(this);
        //获取单元格中的文本
        var text = tdobj.html();
        
        //如果当前单元格中有文本框,就直接跳出方法
        //注意:一定要在插入文本框前进行判断
        if(tdobj.children("input").length>0){
            return false;
        }
        //清空单元格的文本
        tdobj.html("");
        
        inputobj.css("border","0")
                .css("font-size",tdobj.css("font-size"))
                .css("font-family",tdobj.css("font-family"))
                .css("background-color",tdobj.css("background-color"))
                .css("color","#C75F3E")
                .width(tdobj.width())
                .val(text)
                .appendTo(tdobj);
                
        inputobj.get(0).select();
        //阻止文本框的点击事件
        inputobj.click(function(){
            return false;
        });
        
        //处理文本框上回车和esc按键的操作
        //jQuery中某个事件方法的function可以定义一个event参数,jQuery会屏蔽浏览器的差异,传递给我们一个可用的event对象
        inputobj.keyup(function(event){
            //获取当前按键的键值
            //jQuery的event对象上有一个which的属性可以获得键盘按键的键值
            var keycode = event.which;
            //处理回车的情况
            if(keycode==13){
                //获取当前文本框的内容
                var inputtext = $(this).val();
                //将td的内容修改成文本框中的内容
                tdobj.html(inputtext);
            }
            //处理esc的情况
            if(keycode == 27){
                //将td中的内容还原成text
                tdobj.html(text);
            }
        });
        
    });
});
</script>    
    
</body>
</html>

 

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    
</head>
<body>
    
    
    
    <table class="editTable">
      <thead>
      <tr>
        <th>Date</th>
        <th>City</th>
        <th>Venue</th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>June 9th</td>
        <td>Portland, OR</td>
        <td>Crystal Ballroom</td>
      </tr>
      <tr>
        <td>June 10th</td>
        <td>Seattle, WA</td>
        <td>Crocodile Cafe</td>
      </tr>
      <tr>
        <td>June 12th</td>
        <td>Sacramento, CA</td>
        <td>Torch Club</td>
      </tr>
      <tr>
        <td>June 17th</td>
        <td>Austin, TX</td>
        <td>Speakeasy</td>
      </tr>
      </tbody>
    </table>
    
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>    
    <script type="text/javascript">
    $(function(){
    var tds = $("tbody td");
    tds.click(function(){
        //find the td which your click
        tdObj=$(this);
        //td has one input text then do nothing
        if(tdObj.children("input").length >0){
            return false;
        }
        //save the tdObj's value to tdText
        var tdText = tdObj.html();
        //clear the tdObj's value;
        tdObj.html("");
        //create a input text
        //remove the border of the text
        //set the font-size of the text is 16px
        //set the width of the text is the same of the tdObj
        //set the backgroud-color of the text
        //put the td's value into text
        var inputObj = $("<input type='text'/>")
            .css("border","1px dotted #ccc")
            .css("font-size","14px").width(tdObj.width)
            .css("background-color",tdObj.css("background-color"))
            .val(tdText).appendTo(tdObj);
        
        // if is input text then selected
        //inputObj.get(0).select();    //is well in many browns,but not all
        inputObj.trigger("focus").trigger("select"); // do well in all browns
        // if is input text then do nothing
        inputObj.click(function(){
            return false;
        });
        //the input text about "esc" and "Enter" operation
        inputObj.keyup(function(event){
            //get the keycode which you pressed
            var keycode = event.which;
            // do the Enter key
            if(keycode==13){
                //get the input text value
                var inputText = $(this).val();
                //replace the tdText with the inputText
                tdObj.html(inputText);
            }
            //do the esc key
            if(keycode==27){
                //equals the cancle button,roll back do nothing
                tdObj.html(tdText);
            }
        });
    });
});
    </script>
    
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<!DOCTYPE HTML>  
<html>  
  <head>  
    <title>可以编辑的表格</title>  
  </head>  
    
  <body>  
    <table border="1px">  
        <tr>  
            <td>123123</td>    <td>456456</td>  
        </tr>    
        <tr>  
            <td>123123</td>    <td>456456</td>  
        </tr>    
        <tr>  
            <td>123123</td>    <td>456456</td>  
        </tr>  
    </table>
    
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    
    <script type="text/javascript">
    $(function(){  
    //找到所有的td节点  
    $("td").click(tdclick);  
});  
  
function tdclick(){  
      
        var td = $(this);  
        //1.取出当前的文本内容并且保存起来  
        var text = td.text();  
        //2. 清除当前的td内容  
        td.html("");//也可以用empty()方法  
        //3.建立一个input标签  
        var input = $("<input>");  
        //4.设置文本框里面的值是改写后的内容  
        input.attr("value",text);  
        //4.5响应键盘事件,处理回车  
        input.keyup(function(event){  
            //1.判断是否回车按下  
            //结局不同浏览器获取时间的差异  
            var myEvent = event || window.event;  
            var key = myEvent.keyCode;  
            if(key == 13){  
                var inputNode = $(this);  
                //1.保存当前文本框的内容  
                var inputText = inputNode.val();  
                //2.清空td里面的内容  
                inputNode.parent().html(inputText);  
                  
                td.click(tdclick);  
            }  
        });  
          
        input.blur(function(){  
            var inputNode = $(this);  
            var inputText = inputNode.val();  
            inputNode.parent().html(inputText);  
            td.click(tdclick);  
        });  
          
        //5.把文本框就加入到td里面去  
        td.append(input);  
        //6.需要清除td上面的点击事件  
        //6.5高亮数据  
  
        td.unbind("click");  
        //7.提取文本框里面的值  
}  

    </script>
    
    
    
    
    
  </body>  
</html>  

 

 

 

 

今天来演示一个用jquery完成的效果:可编辑的表格。

1.先写一个含有表格的页面jqueryEdit.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>jquery示例3:可修改的表格</title>
    <script type="text/javascript" src="jslib/jquery.js"></script>
    <script type="text/javascript" src="jslib/jqueryEditUseBlur.js"></script>

</head>
<body>
    <table border="1">
        <tbody>
           <tr>
               <td>1234</td>
               <td>5678</td>
           </tr>
        </tbody>
    </table>
</body>
</html>

 

2.书写一个javaScript脚本文件,来完成表格的可编辑效果,jqueryEdit.js:

这个文件中,当输入框修改完后是按回车键提交的,下面一个文件是通过鼠标相对文本框失去焦点来实现提交的,本人认为下面第二种方法比较合乎实际一点。

//在页面加载的时候,让所有的td有一个点击事件
$(document).ready(function(){
    var tdNods = $("td");
    tdNods.click(tdClick);
});

//td点击触发的函数
function tdClick(){
         //1.取出当前td里面的文本内容
         var td = $(this);
         var tdText = td.text();
        //2.清空td里面的文本内容
         td.html(""); //也可以使用td.empty();
        //3.建立一个输入框,也就是input标签
          var input = $("<input>");
        //4.将输入框的内容设为刚才保存的td里面的文本内容
          input.attr("value",tdText);
         //4.5.让文本框能够响应键盘按下的keyup事件,主要是用于处理回车确认
           input.keyup(function(event){
               //1.获取当前用户按下的键值
                  //解决不同浏览器获得事件对象的差异,
                 // IE用自动提供window.event,而其他浏览器必须显示的提供,即在方法参数中加上event
               var myEvent = event || window.event;
               var keyCode = myEvent.keyCode;
               //2.判断是否是回车按下
               if(keyCode == 13){
                   //2.保存当前输入框的内容
                    var input = $(this);
                    var inputText = input.val();//这个地方不能用text(),而是用val()
                   //3.清空td的内容,即去掉输入框
                   var td = input.parent("td");
                   td.empty();
                   //4.将保存的文本内容填充到td中去
                   td.html(inputText);
                   //5.让td重新拥有点击事件
                   td.click(tdClick);
               }
           });
        //5.将输入框加到td中
          td.append(input);  //也可以用input.appendTo(td);
        //5.5 让文本框中的文字被高亮选中
        //需要将jquery对象转化为DOM对象
         var inputDom = input.get(0);
         inputDom.select();
        //6.需要移除td上的点击事件
        td.unbind("click");
};

 

下面这个脚本文件是通过鼠标相对文本框失去焦点来实现提交的jqueryEditUseBlur.js:

下面用红色显示的是与上面文件不一样的地方。

//在页面加载时候,就使td节点具有click点击能力
$(document).ready(function(){
    var tdNods = $("td");
    tdNods.click(tdClick);
});

//td的点击事件
function tdClick(){
    //将td的文本内容保存
    var td = $(this);
    var tdText = td.text();
    //将td的内容清空
    td.empty();
    //新建一个输入框
    var input = $("<input>");
    //将保存的文本内容赋值给输入框
    input.attr("value",tdText);
    //将输入框添加到td中
    td.append(input);
    //给输入框注册事件,当失去焦点时就可以将文本保存起来
    input.blur(function(){
        //将输入框的文本保存
        var input = $(this);
        var inputText = input.val();
        //将td的内容,即输入框去掉,然后给td赋值
        var td = input.parent("td");
        td.html(inputText);
        //让td重新拥有点击事件
        td.click(tdClick);

    });
    //将输入框中的文本高亮选中
    //将jquery对象转化为DOM对象
    var inputDom = input.get(0);
    inputDom.select();
    //将td的点击事件移除
    td.unbind("click");
}

 

3.对上面的效果进行进一步的修改,使之更加人性化(红色字体是修改过的地方)

通过修改使你在修改的过程中文本的内容可以按Esc键撤销还原到修改前的状态

//在页面加载时候,就使td节点具有click点击能力
$(document).ready(function(){
    var tdNods = $("td");
    tdNods.click(tdClick);
});

//td的点击事件
function tdClick(){
    //将td的文本内容保存
    var td = $(this);
    var tdText = td.text();
    //将td的内容清空
    td.empty();
    //新建一个输入框
    var input = $("<input>");
    //将保存的文本内容赋值给输入框
    input.attr("value",tdText);
    //将输入框添加到td中
    td.append(input);
    //给输入框注册事件,当失去焦点时就可以将文本保存起来
    input.blur(function(){
        //将输入框的文本保存
        var input = $(this);
        var inputText = input.val();
        //将td的内容,即输入框去掉,然后给td赋值
        var td = input.parent("td");
        td.html(inputText);
        //让td重新拥有点击事件
        td.click(tdClick);

    });
    input.keyup(function(event){
        //1.获取当前用户按下的键值
              //解决不同浏览器获得事件对象的差异,
             // IE用自动提供window.event,而其他浏览器必须显示的提供,即在方法参数中加上event
           var myEvent = event || window.event;
           var keyCode = myEvent.keyCode;
           //2.判断是否是ESC键按下
           if(keyCode == 27){
               //将input输入框的值还原成修改之前的值
               input.val(tdText);
           }
    });
    //将输入框中的文本高亮选中
    //将jquery对象转化为DOM对象
    var inputDom = input.get(0);
    inputDom.select();
    //将td的点击事件移除
    td.unbind("click");
}

 

 

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!