我认为以下代码
。@foreach($categories as $category)
<tr class="cat-row">
<td class="cat-id">{{$category->id}}</td>
<td>{{$category->name}}</td>
<td><a href="" class="btn btn-danger">Get ID</a></td>
</tr>
@endforeach
如果我想通过单击“获取ID”按钮来获得带有当前行ID的简单警报,我应该在jquery中做什么?
答案 0 :(得分:1)
给“获取ID”按钮一个适当的选择器,如类“ .getid”
$(document).on('click', '.getid', function() {
let id = $(this).closest('tr').find('.cat-id').text();
console.log(id);
});
您必须将侦听器绑定到文档才能应用于动态插入的dom
答案 1 :(得分:0)
这是我的贡献。
与Kapsonfire所写的内容非常相似。
$(document).on('click', '.btn-danger', (e) => {
let target = e.target;
let topmostParent = target.parentElement.parentElement;
let id = $(topmostParent).find('.cat-id').text();
console.log(id);
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<table>
<tr class="cat-row">
<td class="cat-id">123</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">124</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">125</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">126</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
</table>
答案 2 :(得分:0)
这是解决方案
$(".getId").on('click',function() {
let id = $(this).attr('id');
console.log(id);
});
/*PHP File*/
@foreach($categories as $category)
<tr class="cat-row">
<td class="cat-id">{{$category->id}}</td>
<td>{{$category->name}}</td>
<td><a href="" class="btn btn-danger getId" data-id="{{$category->id}}">Get ID</a></td>
</tr>
@endforeach