$.ajax({
url: "ajs/index",
type: "GET",
dataType: "JSON",
success: function (data) {
var output = "";
for (i = 0; i < data.length; i++) {
output += "name:" + data[i] name + "<input type='submit' class='delete' value='Delete' onClick='deleterecord(" + data[i].id + ");'><br>"
}
$("#result").html(output);
// when delete button is clicked.
//$(".delete").click(){
function deleterecord(id) {
alert("sjrg")
$.ajax({
url: "ajs/",
type: "DELETE",
data: "22",
dataType: "html",
success: function (data) {
alert("success")
},
error: function () {
alert("error")
}
}); // delete ajax() closed
} //delete click() closed
} //success function closed
}); //ajax call closed
我使用 .ajax 方法显示了 JSON 响应数据,并为每行添加了删除按钮。
现在,当我单击该按钮时,我需要调用deleterecord(id)函数,但它没有调用它。当我使用代码 $(".delete").click(function())
时,它正在工作,但我需要 onclick 事件,以便我可以在 ajax 数据中使用该 id。
我不明白出了什么问题
最佳答案
问题是因为 deleterecord()
函数不在单击 input
引发的事件范围内。
在这种情况下,更好的模式是使用委托(delegate)事件。我可以看到您尝试了此操作,但已将其注释掉。要传递要删除的特定记录的 id
,请将 data-*
属性添加到附加的 input
:
$.ajax({
url: "ajs/index",
type: "GET",
dataType: "JSON",
success: function(data) {
var output = "";
for (i = 0; i < data.length; i++) {
output += 'name: ' + data[i]name + '<input type="button" class="delete" value="Delete" data-id="' + data[i].id + '"><br>';
}
$("#result").html(output);
}
});
// delegated delete event
$("#result").on('click','.delete', function() {
var id = $(this).data('id'); // use this in the AJAX call as required
$.ajax({
url: "ajs/",
type: "DELETE",
data: "22",
dataType: "html",
success: function(data) {
alert("success")
},
error: function(){
alert("error")
}
});
}
另请注意,我将 input
的 type
从 submit
更改为 button
,因为只有 1 个提交元素每个表格都允许。
关于jquery - 提交按钮 onclick() 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671139/