在另一个单击函数中单击函数被多次调用

时间:2014-01-08 21:23:04

标签: javascript jquery

我第一次与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");
        }

    });

 });

4 个答案:

答案 0 :(得分:2)

此块

$(".deleteIngredient").click(function(e){...

所有 .deleteIngredient元素附加一个clickevent,也包括之前创建的元素。

您必须将此块设置为#addIngredient的点击事件。您可以将删除事件也附加到将来添加的每个元素。

$("#addIngredient").click(function(e){
    // ...
});

$(document).on("click", ".deleteIngredient", function(e){
    // ...
});

答案 1 :(得分:1)

正如其他答案所述,点击处理程序每​​次运行时都会向每个 .deleteIngredient元素添加一个点击处理程序,这会为所有以前的元素添加多个处理程序。 / p>

向列表中添加新项目时,不必为其添加单击处理程序。您可以使用委托创建一个适用于动态添加元素的处理程序:

$("#IngredientForm").on("click", ".deleteIngredient", function(e) {
    ...
});

有关详细信息,请参阅Event binding on dynamically created elements?

答案 2 :(得分:0)

每次外部“点击”事件发生时,您都会为“.deleteIngredient”元素添加另一个“click”处理程序。 .click函数不会删除先前分配的事件处理程序。

您可以使用.unbind或最好使用新版本的jQuery .off删除旧处理程序:

$('.deleteIngredient').unbind('click').click(function(event) {
  // ...
});

不,问题是,在这里我想想你可能想要绑定到你为新成分添加的.deleteIngredient按钮。您获得的代码(基于对$('.deleteIngredient')的引用)将影响该类页面上元素的所有。我的猜测是,您为每个<li>添加了一个按钮或其他内容。因此,您应该做的是在新添加的结构中找到按钮:

$('#IngredientForm ul li:last .deleteIngredient').click(function(event) {
  // ...
});

答案 3 :(得分:0)

请改用此格式

$("#addIngredient").on('click', function() {
   $(this).off();
});
相关问题