[英]Delete a table row is not working with jquery on button click
I have problem when I click on button the table row is not deleted tr id and button id are both same value. 我在单击按钮时没有问题,表格行未删除tr id和button id都是相同的值。 please tell where I am doing wrong
请告诉我我做错了
<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 code jQuery代码
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).attr("id");
$('#' + btn_id + '').remove();
});
});
Thanks in advance 提前致谢
id
need to be unique per element if you are going to use them in jQuery
, and hense your code is not working (As tr
and td
sharing same value for id
). 如果要在
jQuery
使用id
,则每个元素的id
必须唯一,并且会导致代码无法正常工作(因为tr
和td
共享id
值相同)。
Simplify you code through closest() 通过closest()简化代码
$(document).ready(function(){
$('.button_remove').click(function(){
$(this).closest('tr').remove();
});
});
Note:- Remove id
from tr
and td
both. 注意:-分别从
tr
和td
删除id
。 As it's not needed at all. 因为根本不需要。 It will make your
HTML
structure correct and cleaner. 这将使您的
HTML
结构正确,整洁。
Thats because you are using same id for tr
and button
....Try to use data-attributes
here 那是因为您为
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>
And then use jQuery like this 然后像这样使用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.