我试图在模糊最后一个输入后向表中添加行。它工作得很好,但是每次我模糊任何输入时它都会添加一个新行。这是代码:
<script type="text/javascript">
var i = 1;
$(function() {
$('#addNew').click(function() {
$('input').removeClass('last');
$('#all_items tr:last').after('<tr><td><input type="text" name="item_'+i+'" id="items_'+i+'" class="last field" /></td><td>and other input fields</td></tr>');
$.ajax({
url: "js/autocomplete.php?count="+i,
success: function(newhtml){
newhtml += "<";
newhtml += "/script>";
$("head").append(newhtml);
}
});
i++;
});
//on blur click on addNew
$('.last').blur(function() {
$('#addNew').trigger('click');
});
});
</script>
autocomplete.php 就像:
<script>
$(function() {
//this section autocompletes the rows. Disregard for this question
var data = [-data retrieved by a function, working well!-];
$( "#items_'.$count.'" ).catcomplete({ delay: 0, source: data,
select: function(event, ui) {
$("#price_'.$count.'").val(ui.item.price);
$("#category_'.$count.'").val(ui.item.category);
}
});
});
$(".last").blur(function() {
$("#addNew").trigger("click");
});
</script>
和html:
<span id="addNew">Add Item</span>
<table id="all_items">
<tr id="header"><th>Item</th><th>Note</th><th>Quantity</th><th>Price</th></tr>
<tr id="first"><td><input type="text" name="item_0" id="items_0" class="last text" /></td>
<td><input type="text" name="item_note_0" id="item_note_0" /></td>
<td><input type="number" name="quantity_0" id="quantity_0" value="1" /></td>
<td><input type="text" name="price_0" id="price_0" />
<input type="hidden" name="category_0" id="category_0" /></td></tr>
</table>
通过检查元素(Chrome),我可以看到“last”类已被删除,但是当我模糊它们时,这些字段仍会在表格末尾添加一行/输入。我究竟做错了什么?我怎样才能避免他们保持这种行为?