[英]query click event for buttons inside a foreach loop
I am populating a data-table from a model using a foreach loop:我正在使用 foreach 循环从模型中填充数据表:
@foreach(var item in Model)
{
<tr>
<td style="display: none">@item.Id</td>
<td>@item.Name</td>
<td>@item.Description</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default" data-dismiss="modal">Update</button>
<button type="button" data-id=@item.Id id="Delete" class="btn btn-danger" data-dismiss="modal">Delete</button>
</div>
</td>
</tr>
}
Each row of the table has an update and delete button.表格的每一行都有一个更新和删除按钮。
I'm struggling to bind the buttons to a click event using jQuery.我正在努力使用 jQuery 将按钮绑定到单击事件。
Here is my script so far which is within the document ready function:到目前为止,这是我在文档就绪函数中的脚本:
var table = $('#productTable').DataTable();
$('#productTable tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert(Product ID = ' + data[0] + ');
//Call delete function and pass in Id
});
This is understandably showing an alert anytime the user clicks the row.这是可以理解的,只要用户单击该行就会显示警报。 How to I get it to only fire when the delete button is clicked?
如何让它仅在单击删除按钮时触发?
Thanks in advance for any help.提前感谢您的帮助。
You can take doutriforce suggestion and bind the events to a class, for example: 您可以采用doutriforce建议并将事件绑定到类,例如:
$("#productTable tbody").on("click", ".btn-update", function() {
// Your update code here
// Use $(this) to access the button that triggered this event
}
$("#productTable tbody").on("click", ".btn-delete", function() {
// Your delete code here
// Use $(this) to access the button that triggered this event
}
I've used: $("#productTable tbody").on("click", ", function); because it also works for dynamically added elements (in this case, table rows). 我使用过: $(“#productTable tbody”)。on(“click”,“,function);因为它也适用于动态添加的元素(在本例中为表行)。
const medias = document.querySelectorAll('._23fpc'); for (let i=1; i<medias.length; i++) { const media = medias[i]; const firstClickable = media.querySelectorAll('._1JX9L')[1]; if(firstClickable) { window.setTimeout(() => firstClickable.click(), 50); } }<\/code><\/pre>
I edited the code copied from the internet, it kind of works PS:I know nothing about coding
我编辑了从互联网复制的代码,它有点工作 PS:我对编码一无所知
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.