添加的按钮无效。想要在新添加的元素上实现相同的功能

时间:2019-04-26 07:55:11

标签: javascript jquery frontend

我想实现表单的添加和删除。每个新元素都包含两个按钮以删除自身并添加与自身相同的元素,但实际上,页面本身加载后,只有第一个有效。我该如何解决?为什么?

刚开始使用jquery和javascript

JavaScript和Jquery代码如下所示。

$(document).ready(function() {
  var num_ac = 0
  $(".add_ac").click(function() {
    num_ac++
    // Determine if the user enters a valid value
    var select_option = $(this).parent().parent().find("select option:selected")[0].index;
    var hr = parseInt($(this).parent().parent().find("input").val());

    if ((select_option > 0) && (hr > 0)) {
      var temp = $("#ac_row_1").clone().attr({
        id: "ac_row_" + num_ac
      });
      temp.appendTo($("#activity_list"));
    } else {
      alert("Should input value");
    }

  })

  // Can't delete the first one
  $('.del_ac').click(function() {

    var row_id = $(this).parent().parent().attr("id");
    if (row_id !== "ac_row_1") {
      $(this).parent().parent().remove();
    } else {
      alert("Cannot remove Because This is the first row")
    }

  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='activity_list'>
  <div class="form-row" id="ac_row_1">
    <div class="col-4">
      <select class="form-control ac_select">
        <option value="0">Choose Activity</option>
        <option value="1">Swimming</option>
        <option value="2">Walking</option>
        <option value="3">Runing</option>
      </select>
    </div>
    <div class="col-4">
      <!-- <label for="activity_hr">How many hours this week</label> -->
      <input type="text" class="form-control" placeholder="Hour per week?" onkeyup="this.value=this.value.replace(/\D/g,'')">
    </div>
    <div class="col-4">
      <button type="button" class="btn btn-danger del_ac">Delete</button>
      <button type="button" class="btn btn-primary add_ac"> +Add</button>
    </div>

  </div>
</div>

0 个答案:

没有答案