简体   繁体   English

另一个click函数中的click函数被多次调用

[英]click function within another click function is called multiple times

i am in touch with jquery for the first time and ran into this: I am trying to create a dynamic input-form. 我是第一次接触jquery,并遇到了这个问题:我正在尝试创建动态输入表单。 A click function creates a new list-item with another click function nested into it (to provide a remove function for the clicked item). 点击函数会创建一个新的列表项,其中嵌套了另一个点击函数(为被点击的项提供删除功能)。

When i execute the nested click function it appears to be called the number of instances that have been created of it. 当我执行嵌套的click函数时,它似乎被称为已为其创建实例的数量。

Here is the code (i tried to remove as much as possible, but i am not quite sure where the error is - so i guess i left to much stuff in - sorry). 这是代码(我试图删除尽可能多的代码,但是我不太确定错误在哪里-所以我想我留了很多东西-抱歉)。

$("#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");
        }

    });

 });

This block 这个街区

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

attaches a clickevent to all .deleteIngredient elements, also those created before. 将clickevent附加到所有 .deleteIngredient元素(也包括之前创建的元素)。

You have to put this block outsite the click event of #addIngredient . 您必须将此块置于#addIngredient的click事件#addIngredient You can make the delete event to be attached also to every element added in the future. 您可以使delete事件也附加到以后添加的每个元素上。

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

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

As the other answers have noted, the click handler is adding a click handler to every .deleteIngredient element every time you run it, which adds multiple handlers to all the previous elements. 正如其他答案所指出的那样,单击处理程序会在每次运行它时向每个 .deleteIngredient元素添加一个单击处理程序,这会将多个处理程序添加到所有先前的元素中。

When you add a new item to the list, you don't have to add a click handler to it. 将新项目添加到列表时,无需向其添加点击处理程序。 You can use delegation to create a handler one time that will apply to dynamically-added elements: 您可以一次使用委托创建一个处理程序,该处理程序将应用于动态添加的元素:

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

See Event binding on dynamically created elements? 请参阅对动态创建的元素进行事件绑定? for more information. 欲获得更多信息。

Every time that outer "click" event happens, you're adding another "click" handler for the ".deleteIngredient" element(s). 每次外部“ click”事件发生时,您都将为“ .deleteIngredient”元素添加另一个 “ click”处理程序。 The .click function does not remove previously-assigned event handlers. .click函数不会删除以前分配的事件处理程序。

You can get rid of old handlers with .unbind or, preferably with new versions of jQuery, .off : 你可以摆脱旧的处理程序与.unbind或者,最好使用jQuery,新版本.off

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

No, the thing is, here I think you probably want to bind to the .deleteIngredient button that you're adding for the new ingredient. 不,问题是,我您可能想绑定到要为新成分添加的.deleteIngredient按钮。 The code you've got — based on the reference to $('.deleteIngredient') — will affect all of the elements on the page with that class. 您所获得的代码(基于对$('.deleteIngredient')的引用$('.deleteIngredient')将影响该类页面上的所有元素。 My guess here is that you're adding a button or something for each <li> . 我的猜测是,您要为每个<li>添加一个按钮或其他东西。 Thus, what you should probably be doing is finding the button inside the newly-added structure: 因此,您可能应该做的是在新添加的结构中找到按钮:

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

Use this format instead 改用这种格式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM