我正在创建使用jQuery添加到现有表的行。我希望这些行中的每一行都包含一个删除按钮,该按钮调用一个要求密码的方法,然后删除该行。为此,我创建了一个这样的新行:
$('tbody').append('<tr id="row' + index + '"><th>' + name + '</th>' + '<th>' + zutaten + '</th>' + '<th>' + foodtype + '</th>' + '<th><button onclick="showPwdDialog(' + index + ');">Delete</button></th></tr>');
如您所见,我试图以行索引作为参数调用showPwdDialog方法。但是,这似乎不起作用。我做错了什么?
答案 0 :(得分:1)
我不认为你的onclick处理程序在通过像你这样的html片段构造元素时被正确绑定。
相反怎么样?
var index = 0;
function showPwdDialog(i) {
if (confirm("Delete this row?"))
$("#test #row"+i).remove();
}
function addRow(){
var i = ++index;
var row = $("<tr>")
.attr("id", "row"+(i))
.append($("<th/>").html("name"))
.append($("<th/>").html("zutaten"))
.append($("<th/>").html("name"))
.append($("<th/>")
.append($("<button/>")
.text("Delete")
.on("click", function(){
showPwdDialog(i);
})
)
);
/* add row to table here */
}