我正在使用jQuery在表上添加或编辑行。如果我尝试在此处编辑一行,它可以工作,但如果我添加新行,则编辑不起作用。
我的脚本 :
//Add a row
$("#btnadd").click(function(){
$('.table tr:last').after('<tr>' +
"<td>Name</td>"+
'</tr>');
});
//Edit a row (took from a tutorial)
$(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");
});
});
});
我对Jquery很陌生,所以我很确定我错过了一些明显的东西。
$('table').on('click','tr', function(){
$(this).css('color','green');
});
$('button').on('click',function(){
var newRow = $('<tr class="row"><td>New</td><td>Row</td><td>29</td></tr>');
$('table').append(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
<button>Add</button>
我认为这是因为页面加载时单击事件绑定到表。加载页面后输入的任何新行都缺少此事件。现在,单击 TR(表格行)时将触发您的函数。由于加载页面时该(新)表行不存在,因此事件不会绑定到新行。
您可以通过将 click-event 绑定到表来解决此问题。通过这样做,它将起作用。我做了一个小提琴,如果你点击它,tr 是绿色的。它也适用于新添加的表格行
$('table').on('click','tr', function(){
//do your edits
});
我认为您在副本中犯了一个小错误,因为您添加行的单击功能未正确关闭?