[英]Onclick event doesn't work after AJAX in JQuery issue
这是Jquery代码:
$("#save").on ('click', function(){ // save new person
var new_name = $("#name").val();
var new_age = $("#age").val();
var formData = { name : new_name, age : new_age };
$.ajax({
url : "ajax.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR){
get_old_html = $("#result_json").html(); // getting current html data
var array = JSON.parse(data); // getting the JSON
var html = "";
for (var i = 0 ; i < array.length; i++){
var split = array[i].split("||");
html = html + "<tr><td>"+ split[1] +"</td><td>"+ split[2] +"</td><td><center><a href ='#' class ='delete_person' id ='"+ split[0] +"'>X</a></center></td></tr>"; // create the new html with the new item
}
$("#result_json").html(html + get_old_html); // add the new html and the content of it
$("#add_new_person").hide();
$("#add_person").show();
//mesaj de confirmare
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
$(".delete_person").on('click',function(){ //delete person
id = $(this).attr("id");
var formData = { id : id };
$.ajax({
url : "ajax.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR){
var remove = JSON.parse(data); // getting the JSON
if (remove == "success"){
$("#"+id).closest("tr").remove();
}
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
事实是,当我保存一个新人,然后要删除该人时,类“ delete_person”上的onclick事件不起作用。 但是,当我刷新页面时,它可以工作。 我该怎么办 ? 并且所有这些都包含在$( document ).ready(function() { });
.delete-person
是在进行 AJAX调用后动态添加到DOM中的元素。 由于您的jQuery脚本是在DOMready上运行的(当运行时.delete-person
不存在时),因此click事件不会绑定到该元素。
行$('.delete-person').on('click', function() { ... });
在功能上与$('.delete-person').click(function() { ... });
。 要点是要将click事件处理程序附加到元素.delete-person
,该元素在运行时不存在于DOM中。
相反,请监听源自.delete-person
的click事件,该事件正在冒泡至document
对象:
$(document).on('click', '.delete-person', function() {
// Do stuff here to delete person
});
上面的代码的不同之处在于,即使在document
对象上,您也在侦听单击,但是验证click事件是否源自具有.delete-person
类的子元素。 由于单击事件将始终冒泡到document
而不管对象在运行时是否存在,因此您可以通过这种方式删除人员;)
确保响应数据和使用
$(this).closest("tr").remove();
或尝试:
$(".delete_person").on('click',function(){
var element = $(this);
然后
$(element).closest("tr").remove();
我认为您应该只添加一个本机javascript函数
for (var i = 0 ; i < array.length; i++){
var split = array[i].split("||");
html = html + "<td><a href='#' onlick='deletePerson("+split[1]+")'>Delete</a></td>" // create the new html with the new item
}
然后超过您的$(document)
function deletePerson(id){
var person_id = id ;
//ajax code here
}
每当我有一个具有使用jquery的删除功能的动态表时,这就是我要做的
这是因为该元素在文档中不存在。 您需要使用
$(document).on("click", "selector", function(){do something});
希望这可以帮助 :)
快乐学习:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.