无法删除动态创建的div

时间:2019-07-16 13:44:20

标签: javascript jquery html

用户可以通过单击特定行的“-”按钮来删除新的字段输入行。用户还可以添加新的字段输入行。我编写的JS代码适用于现有行,但不适用于通过单击“ +”按钮添加的任何新动态创建的行。

我尝试更改

$(".remove-current-ing").click(function() {...}

$(".remove-current-ing").on('click', function() {...}

HTML代码:

<div class="row card z-depth-1">
        <h3><i class="fas fa-pizza-slice"></i> Ingredients</h3>
        {% for ing in recipe.ingredients %}
        <div class="input-field ingredients col s12">
            <input id="ingredients" name="ingredients" type="text" placeholder="Ingredient (one per line)" class="form-control validate" value="{{ ing|capitalize }}" required>
            <label for="ingredients"></label>
            <!--BUTTON THAT ISN'T WORKING ON DYNAMICALLY CREATED ROWS-->
            <a class="waves-effect waves-light btn remove-current-ing">
                <i class="fas fa-minus material-icons" aria-hidden="true"></i>
            </a>
        </div>
        {% endfor %}
        <!--Add Ingredient Row Btn-->
        <button type="button" class="waves-effect waves-light btn add-ing">
            <i class="fas fa-plus material-icons" aria-hidden="true"></i>
        </button>

        <!--Remove Ingredient Row Btn-->
        <button type="button" class="waves-effect waves-light btn remove-ing">
            <i class="fas fa-minus material-icons" aria-hidden="true"></i>
        </button>
    </div>

JS代码:

 let ingCount = $(".ingredients").length;
    // Add new line
    $(".add-ing").click(function() {
        // Clone line, insert before add/remove btns and clear existing values
        $(".ingredients:first").clone().insertBefore(".add-ing").find("input[type='text']").val("");
        // Ensures original line is never removed
        ingCount += 1;
    });
    // Remove last line
    $(".remove-ing").click(function() {
        // Ensure that the first line can't be removed
        if (ingCount > 1) {
            $(".ingredients:last").remove();
            ingCount -= 1;
        }
    });

/* Remove the current ingredient (edit_recipe.html) */
/* CODE THAT ISN'T WORKING ON DYNAMICALLY CREATED ROW */
$(".remove-current-ing").on('click', function() {
    // Ensure that the first line can't be removed
    if (ingCount > 1) {
        $(this).parent().remove();
        ingCount -= 1;
    }
});```

.remove-current-ing按钮适用于预先存在的行并将其删除,但不适用于动态创建的新行(按下时无反应)。

2 个答案:

答案 0 :(得分:0)

替换

$(".remove-current-ing").on('click', function() {

$(document).on('click', ".remove-current-ing", function() {

这称为委托侦听器-概念是,任何单击事件都会在DOM上冒泡,直到它到达连接您的侦听器的document。将选择器字符串作为第二个参数添加到$.on()使得jQuery仅在所单击的元素与选择器匹配时才执行处理函数。

答案 1 :(得分:0)

您必须使用后期绑定。它允许您通过适当的属性将事件绑定到当前不存在的元素上

$(document).on('click', ".remove-current-ing", function() {
  // Ensure that the first line can't be removed
  if (ingCount > 1) {
      $(this).parent().remove();
      ingCount -= 1;
  }
});```