使用jQuery在DOM中添加后,事件单击无法正常工作

问题描述 投票:0回答:1

我知道它看起来像一个基本问题。我一直在玩delegation,但仍然得到相同的结果。

我正在尝试使其工作列表中的删除按钮,它只适用于第一个,但如果我添加一个新的它将无法正常工作

  //variables
  let $questions = $('.quiz-questions');
  let $tableOptionQuestions = $('.survey-list-service');
  let $addNewOption = $('.add-option');
  let $removeOption = $('.remove-option');
  
  //events
  $addNewOption.on("click", addNewOptionFunc );
  $removeOption.on("click", removeOptionFunc );

  //add new option
  function addNewOptionFunc (e) {
    let $optionRow = $(this).prev().children('tbody').children('tr').first();
    $optionRow.clone().appendTo( "tbody" );
  }
  
  //remove option
  function removeOptionFunc (e) {
    let $optionRow = $(this);
    let $sizeRow = $tableOptionQuestions.find('tbody tr').length; 
    
    // if( $tableOptionQuestions.find('tbody tr').length != 1 ) {
      $optionRow.closest('tr').remove();
    // }    
    
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quiz-questions">

  
  <section>
  <table class="survey-list-service">
    <thead>
      <tr>
        <th>Name</th>       
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="text" value=""></td>
        <td><button class="button button-primary remove-option">remove</button></td>
      </tr>
    </tbody>
  </table>
  
  <button class="button button-primary add-option">Add </button>

  </section>

</div>
jquery
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.