在JavaScript中动态添加删除按钮

时间:2018-04-12 02:42:43

标签: javascript jquery

我很难让我的删除按钮动态删除项目。当我添加新配料时,按钮出现但没有功能。

$(document).ready(function () {
        getRecipe();
        $(".btn-primary").on("click", addIngredient);
        $(".btn-default").on("click", deleteIngredient);
    });

    var recipe = {
        title: "Pizza",
        servings: 4,
        ingredients: ["cheese", "sauce", "flour", "pepperoni"]
    };

    var button = "<button type=\"button\" class=\"btn btn-default delete btn-xs\"><span class=\"glyphicon glyphicon-minus-sign\"></span></button>";

    function getRecipe() {


        $("#title").append(recipe.title);
        $("#servings").append(recipe.servings);


        for (var i = 0; i < recipe.ingredients.length; i++) {
            $("#ingredients ul").append("<li>" + recipe.ingredients[i] + " " + button + "</li>");

        };
    };

    function addIngredient() {
        var newIngredient = $(".form-control").val();
        $(".form-control").val(newIngredient);
        $("#ingredients ul").append("<li>" + newIngredient + " " + button + "</li>");

    };

    function deleteIngredient() {
        $(this).closest("li").remove();
    };

2 个答案:

答案 0 :(得分:0)

当按钮尚不存在时,您正在添加onclick处理程序。每次添加一个按钮时调用它实际上得到处理程序:

function addIngredient() {
    var newIngredient = $(".form-control").val();
    $(".form-control").val(newIngredient);
    $("#ingredients ul").append("<li>" + newIngredient + " " + button + "</li>");

    // after, bind here to register handler to new element
    $(".btn-default").on("click", deleteIngredient);
};

答案 1 :(得分:0)

我更喜欢创建实际的Javascript对象而不是添加HTML文本。一个好的编辑器将帮助检查Javascript代码,并使您不必在任何地方逃避引号。

这主要是普通的旧JavaScript,可以做你想要的。

// returns the button that deletes the element provided.
var CreateADeleteObjButton = function(someHtmlElement) {
    var button = document.createElement("button");
    button.type = "button";
    button.className = "btn btn-default delete btn-xs";
    var span = document.createElement("span");
    span.classNAme = "glyphicon glyphicon-minus-sign";
    button.appendChild(span);
    // below is how the button actually deletes something when it is clicked.
    button.onclick = function() {
        // these lines could probably be replaced by the jquery version
        // $(someHtmlElement).remove();
        var parent = someHtmlElement.parent;
        parent.removeChild(someHtmlElement);
    };
    return button;
}

function addIngredient() {
    var newIngredient = $(".form-control").val();
    $(".form-control").val(newIngredient);
    var aLink = document.createElement("li");
    // you can put the button where you like, but following your code
    // I am adding it to the end of the li element.
    alink.appendChild(CreateADeleteObjButton(alink));
    // I assume that #ingredients is an id for the ul, it not, simply add an id to the UL element and put it below.
    document.getElementById("#ingredients").appendChild(alink);
};