我一直在为此烦恼,为什么它不能正常工作。
我正在使用 .after 方法创建一个新表行,如下所示:
$('#milestone_add_final').submit(function(event){
if (($('#milestone_date').eq(0).val().length == 0) || ($('#milestone_description').eq(0).val().length) == 0) { alert("You forgot to enter a value!"); return false; }
$.blockUI();
event.preventDefault();
var values = $(this).serialize();
$.ajax({
url: "submit.php",
type: "post",
data: values,
success: function(response){
var json = $.parseJSON(response);
$('.milestones tr:first').after("<tr id=\""+json.milestone_id+"\"><td class=\"date smallest\">"+json.milestone_date+"</td><td class=\"description edit_input\" id=\""+json.milestone_id+"\">"+json.milestone_description+"</td><td class=\"action smallest\"><a class=\"delete\" href=\"#\">x</a></td></tr>");
$('#milestone_date').val('').blur();
$('#milestone_description').val('').blur();
},
error:function(){
alert(failure);
}
});
});
除了已经在 html 代码中配置的硬编码之外:
<table id="milestones">
<tr><th class="date"><form id="milestone_add_final" method="post"><input type="text" name="milestone_date" id="milestone_date" placeholder="Date"></th><th class="description"><input type="text" name="milestone_description" id="milestone_description" placeholder="Description"></th><th class="action"><button type="submit">+</button><input type="hidden" name="action" value="milestone_add_final"></form></th></tr>
<tr id="2"><td class="date smallest">22/02/13</td><td class="description edit_input" id="todo_description_153">qfhds sqkjf lhfsjlsqf hjlksqj</td><td class="action smallest"><a href="#" class="delete">x</a></td></tr>
<tr id="4"><td class="date smallest">22/02/13</td><td class="description edit_input" id="todo_description_153">xxxxx</td><td class="action smallest"><a href="#" class="delete">x</a></td></tr>
</table>
当我尝试删除已经存在的表行时,它可以正常工作 - 但是当我尝试对动态添加的行(通过 jQuery)执行相同操作时,它不起作用。我不同意为什么它不起作用。
$('table#milestones td a.delete').on('click', function()
{
if (confirm("Are you sure you want to delete this milestone?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'milestone=' + id + '&action=milestone_delete_final';
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "delete.php",
data: data,
cache: false,
success: function()
{
parent.remove();
}
});
}
});