如何选择由ajax附加的选择器而不刷新页面



我通过ajax(jquery)创建一个客户端列表,包括'添加客户端','编辑客户端','删除客户端'。

使用ajax,我编写了代码,使用$("#list").append(…)将新客户端添加到我的列表中,如下所示:

$.ajax({
type: "POST",
url: "traitement.php",
data: {nom, prenom, email},
dataType: "json",
success: function () {
$("#reponse")
.hide()
.html("<span class='sucess'> Client ajouté avec succès. </span>")
.fadeIn(1000);  
$("input").val('');
$("#list").append("<tr id='New'><td>" + id + "</td><td>" + nom + "</td><td>" + prenom + "</td><td>" + email + "</td>"+"<td id = 'editNew'><button><i class='fa fa-edit'></i></button></td>"+"<td  id = 'deleteNew'><button><i class='fa fa-trash-o'></i></button></td>"+"</tr>");
},
error: function() {
$("#reponse")    
.html("<span class='error'> Une erreur s'est produite. </span>");
}            
});

现在,我想选择#editNew或# deletennew来修改我的客户端列表,而不刷新页面。

问题是在追加"#new"到我的HTML通过ajax。该元素**已显示,但尚未在页源**中显示。所以,我不能选择它。

你能给我一些想法,我怎么能添加一个元素,选择这个元素没有刷新页面与ajax,请!

谢谢你。

让我们试试这个代码,希望能对你有所帮助。

$.ajax({
type : "POST", 
url : "traitement.php", 
data : {nom, prenom, email},
beforeSend: function() {},
success: function(response) {
$("input").val('');
$("#list").html('');
if (response.notification) {
var list_tr = '';
response.data.forEach(d => {
list_tr += "<tr id='New'><td>" + d.id + "</td><td>" + d.nom + "</td><td>" + d.prenom + "</td><td>" + d.email + "</td>"+"<td id = 'editNew'><button><i class='fa fa-edit'></i></button></td>"+"<td  id = 'deleteNew'><button><i class='fa fa-trash-o'></i></button></td>"+"</tr>";
});
} else {
$("#list").html("<tr><td colspan='5'><p></p></td></tr>");
}
$("#list").html(list_tr);
},
complete: function(response) {
if (response.notification) {
$("#reponse")
.html("<span class='sucess'> Client ajouté avec succès. </span>")
.fadeIn(1000);
} else {
$("#reponse")
.html("<span class='danger'> Client ajouté avec fail. </span>")
.fadeIn(1000);
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log( 'The following error occured: ' + textStatus, errorThrown );
}
});

最新更新