我的项目是 C# MVC。
我有一个表,其最后一行包含一个带有“添加”按钮的下拉列表。单击“添加”按钮后,将通过 JQuery 将一行添加到表中。这工作得很好。
添加的行的一部分是“删除”按钮,我想用它来删除该行。
奇怪的是,JQuery 没有拾取“删除”按钮的单击事件。它与“添加”按钮完全相同,只是 ID 不同。有谁知道为什么会这样吗?代码如下。
$('#AddBuyCondition').click(function () {
alert("abc");
var conditionID = +$("#BuyConditionList").val();
var conditionText = $("#BuyConditionList").find('option:selected').text();
$('#BCDropDownRow').before('<tr><td>' + conditionText + '</td><td><button id="RemoveBuyCondition" type="button" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
});
$('#RemoveBuyCondition').click(function () {
alert("rbc");
});
最佳答案
您需要使用event delegation 在这里,因为您的按钮已动态添加到 DOM:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
$('#BuyConditions').on('click', '#RemoveBuyCondition', function() {
alert("rbc");
});
所以基本上在您的情况下,事件委托(delegate)将帮助您将单击事件附加到动态添加的按钮元素。
此外,为了防止重复 id
,您应该为按钮使用 class 而不是 id
。
......'</td><td><button type="button" class="RemoveBuyCondition btn btn-default btn-xs">......
然后你可以将 jQuery 代码更改为:
$('#BuyConditions').on('click', '.RemoveBuyCondition', function() {
alert("rbc");
});
关于c# - 按钮点击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22525852/