这里仅演示一行 , 其原理都相同
<body>
<table class="comment-table">
<thead>
<tr>
<th>编号</th>
<th>所属文章</th>
<th>评论内容</th>
<th>评论者</th>
<th>评论时间</th>
<th>评论状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="id值"></td>
<td>一定会更好</td>
<td>加油</td>
<td>悠悠</td>
<td>2020-03-02</td>
<td>未审核</td>
<td><button class="comment-delete">删除</button></td>
</tr>
</tbody>
</table>
</body>
这里可以看见与取值按钮同行的其他元素都在td中,并且同属一个父元素tr , 所以在获取同行其他元素的时候可以先确定他们的父元素 .
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.js"></script>
<script>
$(function(){
$('.comment-delete').click(function(){
var id = $(this).closest('tr').find(':checkbox').val();
console.log(id);
})
})
</script>
在点击某个元素的时候 $(this) 可以选中当前被点击的元素 .closest(‘tr’) 是选中离之最近的一个标签为tr的元素 .find(’:checkbox’) 是从所选中的元素中寻找type是checkbox 的元素 , 写法等同于.find(’[type==checkbox]’) , .val() 是获取选中元素的value值
这样写最终可以取到复选框的value值,效果为
同样的可以类推到其他同行元素 , 再比如通过第几个位置选中同行元素 , 这里选中第tr中第6个td中的text内容
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.js"></script>
<script>
$(function(){
$('.comment-delete').click(function(){
var id = $(this).closest('tr').find(':checkbox').val();
console.log(id);
var id1 = $(this).closest('tr').find('td:nth-child(6)').text();
console.log(id1);
})
})
</script>
其他元素可同理选中
选中以后就好办了,如果要修改文字就text(‘需要修改的文字’),修改value值用val(‘需要修改的值’) , 这里修改第3个td评论内容的文字
<script>
$(function(){
$('.comment-delete').click(function(){
var id = $(this).closest('tr').find(':checkbox').val();
console.log(id);
var id1 = $(this).closest('tr').find('td:nth-child(6)').text();
console.log(id1);
$(this).closest('tr').find('td:nth-child(3)').text('修改的评论');
})
})
</script>
或者向里面加按钮
<script>
$(function(){
$('.comment-delete').click(function(){
var id = $(this).closest('tr').find(':checkbox').val();
console.log(id);
var id1 = $(this).closest('tr').find('td:nth-child(6)').text();
console.log(id1);
$(this).closest('tr').find('td:nth-child(3)').text('修改的评论');
//添加按钮到第六个td中
$(this).closest('tr').find('td:nth-child(6)').html(`<button class="comment-delete">未审核</button>`);
})
})
</script>
这个是自己试了很多方法以后觉得还算简单的方法 , 希望刚入坑的新人可以少走弯路 , 自己测试真是太累了