javascript - 另一个单击函数中的单击函数被多次调用

标签 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");
        }

    });

 });

最佳答案

这个区 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/

相关文章:

javascript - 如何根据兄弟组件设置的 URL 重新加载 React 组件?

javascript - ReactJS:表单 onSubmit 无法调用回调

jquery - 从下拉列表中获取文本并使用 JQuery 将其插入到输入文本中?

php - jquery错误NS_ERROR_XPC_BAD_CONVERT_JS : in FF works but not on Chrome

javascript - Python SimpleHttpServer 指南

javascript - 使用 javascript/jquery,更新一组图像的 src 的最佳方法是什么?

JavaScript 无法在生产环境中运行

javascript - 如果没有特定元素可见,则 Angular2 显示元素

jquery - 选择框单击功能不再检测到 Bootstrap

javascript - js函数中的'语法错误,意外标记='