![](/img/trans.png)
[英]CodeIgniter 3: Insert/delete html table row on button click with jquery
[英]Delete a table row is not working with jquery on button click
我在單擊按鈕時沒有問題,表格行未刪除tr id和button 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
必須唯一,並且會導致代碼無法正常工作(因為tr
和td
共享id
值相同)。
通過closest()簡化代碼
$(document).ready(function(){
$('.button_remove').click(function(){
$(this).closest('tr').remove();
});
});
注意:-分別從tr
和td
刪除id
。 因為根本不需要。 這將使您的HTML
結構正確,整潔。
那是因為您為tr
和button
使用了相同的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.