首页 > 语言 > JavaScript > 正文

jQuery(非HTML5)可编辑表格实现代码

2024-05-06 14:20:34
字体:
来源:转载
供稿:网友
功能:
单击单元格选中,选中过程中使用方向键更换选中的单元格,选中过程中按回车键或者直接双击单元格进入可编辑状态,单元格失去焦点时保存修改的内容。

主要实现思路:
选中,移动选中区域等都是依靠jQuery强大的API进行实现的。而可编辑的单元格实际上是在选中单元格时,在单元格上面添加个input输入域,动态的更新数据

源代码:
HTML代码:
代码如下:
<table class="editableTable">
<thead>
<tr>
<th>Item1</th>
<th>Item2</th>
<th>Item3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="editable simpleInput">arthinking</td>
<td class="editable simpleInput">Jason</td>
<td class="editable simpleInput">itzhai</td>
</tr>
<tr>
<td class="editable simpleInput">arthinking</td>
<td class="editable simpleInput">Jason</td>
<td class="editable simpleInput">itzhai</td>
</tr>
<tr>
<td class="editable simpleInput">arthinking</td>
<td class="editable simpleInput">Jason</td>
<td class="editable simpleInput">itzhai</td>
</tr>
</tbody>
</table>

CSS代码:
代码如下:
body{
text-shadow:#FFFFFF 1px 1px 1px;
}
.editableTable{
width: 220px;
padding: 10px;
background-color: #DDEEF6;
border:1px solid #DDEEF6;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
}
.editableTable thead{
background:#FFFFCC;
}
td{
background:#66CCFF;
cursor:pointer;
}
.selectCell{
background:#6699FF;
}

JS代码:
代码如下:
var EdTable = function(){
// 给单元格绑定事件
function initBindGridEvent(){
$("td.editable").unbind();
// 添加单元格点击事件
addGridClickEvent();
// 添加单元格双击事件
addGridDbClickEvent();
// 添加键盘事件
addGridKeyPressEvent();
}
// 给单元格添加单击事件
function addGridClickEvent(){
$("td.simpleInput").bind("click",function(){
$('.simpleInput').each(function(){
$(this).removeClass("selectCell");
});
// 给选中的元素添加选中样式
$(this).addClass("selectCell");
});
}
//给单元格添加双击事件
function addGridDbClickEvent(){
$("td.simpleInput").bind("dblclick",function(){
$('.simpleInput').each(function(){
$(this).removeClass("selectCell");
});
var val=$(this).html();
var width = $(this).css("width");
var height = $(this).css("height");
$(this).html("<input type='text' onblur='EdTable.saveEdit(this)' style='width:"+ width +";height:"+ height +"; padding:0px; margin:0px;' value='"+val+"' >");
$(this).children("input").select();
});
}
// 给单元格添加键盘事件
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选