簡體   English   中英

刪除表行不適用於單擊按鈕時的jQuery

[英]Delete a table row is not working with jquery on button click

我在單擊按鈕時沒有問題,表格行未刪除tr idbutton id都是相同的值。 請告訴我我做錯了

<tr id="<?php echo $result->id;?>">

  <td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>

  <td><button type="button" name="remove" id="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>

</tr>

jQuery代碼

$(document).ready(function() {
  $('.button_remove').click(function() {
      var btn_id = $(this).attr("id");
      $('#' + btn_id + '').remove();
  });
});

提前致謝

如果要在jQuery使用id ,則每個元素的id必須唯一,並且會導致代碼無法正常工作(因為trtd共享id值相同)。

通過closest()簡化代碼

$(document).ready(function(){ 
  $('.button_remove').click(function(){ 
      $(this).closest('tr').remove();
  });
});

注意:-分別從trtd刪除id 因為根本不需要。 這將使您的HTML結構正確,整潔。

那是因為您為trbutton使用了相同的ID ....嘗試在此處使用data-attributes

<tr id="<?php echo $result->id;?>">
  <td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
  <td><button type="button" name="remove" data-row="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
<tr>

然后像這樣使用jQuery

$(document).ready(function() {
  $('.button_remove').click(function() {
    var btn_id = $(this).data("row");
    $('#' + btn_id + '').remove();
  });
});

 $(document).ready(function() { $('.button_remove').click(function() { $(this).parents().eq(1).remove(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><input type="text" value="1"/></td> <td><button type="button" class="button_remove">X</button></td> </tr> <tr> <td><input type="text" value="2"/></td> <td><button type="button" class="button_remove">X</button></td> </tr> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM