[英]Adding a record to HTML table using Jquery
我在jquery中发现了这个非常不错的脚本,可以双击编辑表的内容。 现在,我正在尝试通过添加按钮向表添加更多功能。 我要添加的第一个功能是“添加”。 看看我的小提琴 ,事情会很清楚
此时一切似乎都正常。 但是,当我单击添加添加一行时,它不允许我像其他行一样编辑内容
的HTML
<table class="editableTable">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Pedro Fernandes</td>
<td>pedro.ferns@myemail.com</td>
<td>(21) 9999-8888</td>
</tr>
</tbody>
</table>
<td style="text-align:center;">
<button onclick="addrecord()" >Add</button></td>
JQUERY
$(function () {
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function () {
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});
function addrecord(){
$('<tr><td>004</td><td></td><td></td><td></td></tr>').appendTo('table');
}
更改
$("td").dblclick(function () {
至
$(".editableTable").on("dblclick", "td", function () {
两者之间的区别在于,前者将事件添加到现有TD上,但不会在您试图实现的任何动态添加的TD上添加相同的事件。 然而,后者也照顾动态添加的任何TD。
使其可双击的代码仅在开始时运行,因此该代码将不适用于您创建的任何新行。 一个真正肮脏的技巧是将代码复制到您的函数中,尽管当然还有其他方法。
function addrecord(){
$('<tr><td>004</td><td></td><td></td><td></td></tr>').appendTo('table');
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function () {
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
}
好了,您有静态表,在每个td上注册事件侦听器,然后添加新行。 当然,在这一点上没有点击监听器。 创建新行后,您需要注册侦听器:
var row = $('<tr><td>004</td><td></td><td></td><td></td></tr>');
row.find("td").dblclick(mylistener)
row.appendTo('table');
.live可以解决问题。
$(function () {
$("td").live("dblclick",function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function () {
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});
function addrecord(){
$('<tr><td>004</td><td></td><td></td><td></td></tr>').appendTo('table');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.