我第一次接触jquery并遇到了这个:我正在尝试创建一个动态输入表单。单击函数创建一个新的列表项,其中嵌套了另一个单击函数(为单击的项提供删除函数)。
当我执行嵌套点击函数时,它似乎被称为已创建的实例数。
这是代码(我尝试删除尽可能多的内容,但我不太确定错误在哪里 - 所以我想我留下了很多东西 - 抱歉)。
$("#addIngredient").click(function(e){
e.preventDefault();
var prefix = "form-"
var last = $("#IngredientForm ul li").last().html();
$("#IngredientForm ul").append("<li>"+last+"</li>");
var name = $("#IngredientForm ul li:last input").attr("name");
name = name.replace(prefix,'');
var count = parseInt(name[0]);
count += 1;
$("#IngredientForm ul li:last input").attr("name",prefix+count+"-weight")
$("#IngredientForm ul li:last select").attr("name",prefix+count+"-ingredient")
$("#IngredientForm ul li:last input").attr("id","id_"+prefix+count+"-weight")
$("#IngredientForm ul li:last select").attr("id","id_"+prefix+count+"-ingredient")
$("#id_form-TOTAL_FORMS").val(count+1);
$(".deleteIngredient").click(function(e){
e.preventDefault();
var aktuell = $(this).closest('li');
var formCount;
name = aktuell.children('input').attr("name");
name = name.replace(prefix,'');
counter = name.replace("-weight",'');
formCount = parseInt($("#id_form-TOTAL_FORMS").val());
aktuell.remove();
--formCount;
$("#id_form-TOTAL_FORMS").val(formCount);
for (var i = parseInt(counter); i<formCount; i++){
var newName = "form-"+(i);
$("#id_form-"+(i+1)+"-weight").attr("name",newName+"-weight");
$("#id_form-"+(i+1)+"-ingredient").attr("name",newName+"-ingredient");
}
});
});
最佳答案
这个区 block
$(".deleteIngredient").click(function(e){...
将 clickevent 附加到所有 .deleteIngredient
元素,以及之前创建的元素。
您必须将此 block 放在 #addIngredient
的点击事件之外。您可以将删除事件附加到将来添加的每个元素。
$("#addIngredient").click(function(e){
// ...
});
$(document).on("click", ".deleteIngredient", function(e){
// ...
});
关于javascript - 另一个单击函数中的单击函数被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21006815/