如何为以编程方式创建的按钮添加onclick函数 [英] How to add onclick function for programmatically created button
问题描述
我有一个表,其中在单击按钮时使用javascript添加行.这是我的代码:
I have a table wherein I add rows using javascript when a button is clicked. Here's my code:
$("#addToDisplay").click(function (event) {
$("#tblProducts").removeClass("hide");
var counter = 1;
event.preventDefault();
counter++;
var newRow = "<tr><td>" + $("#txtProducts").val() + "</td><td>" + ("#txtQty").val() "</td><td><input type='button' value='Remove' id='btnRemove' /></td></tr>";
$("#tblProducts").append(newRow);
});
我的问题是,由于我在每行中添加了删除按钮,因此将其包括在变量newRow中,如何为其添加onClick事件,以便如果单击删除按钮,则将删除相应的行?
My problem is since I add the remove button per row, hence including it inside the variable newRow, how do I add an onClick event for it so that if I clicked the remove button the corresponding rows would be removed?
推荐答案
首先在您的动态按钮上放置一个通用类
first place a common class on your dynamic button
像<input type='button' value='Remove' class='remove' />
一样,如果要在其中输入ID,请为输入按钮指定一个唯一的ID.您可以使用代码中使用的计数器变量来制作唯一ID.
like <input type='button' value='Remove' class='remove' />
and give a unique id to your input button if you want id there. you can make unique id by using counter variable, which you are using in your code.
$("#addToDisplay").click(function (event) {
$("#tblProducts").removeClass("hide");
var counter = 1;
event.preventDefault();
counter++;
var newRow = "<tr><td>" + $("#txtProducts").val() + "</td><td>" + $("#txtQty").val() + "</td><td><input type='button' value='Remove' id='btnRemove"+counter+"' class='remove' /></td></tr>";
$("#tblProducts").append(newRow);
});
并添加以下代码,它将删除"remove"按钮的父行.
and add the following code, it will remove the parent row of remove button.
$("#tblProducts").on('click', '.remove', function(){
$(this).closest('tr').remove();
})
或者,如果您正在生成动态ID,则可以对其进行更改以使其与
Or If you are generating your dynamic ids, you can change it to work with id like
$("#tblProducts").on('click', '[id^=btnRemove]', function(){
$(this).closest('tr').remove();
});
这篇关于如何为以编程方式创建的按钮添加onclick函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!