我的应用程序将新帖子添加到 <ul>
使用 .prepend() 然后使用 .ajax() 函数将其添加到数据库,如下所示:
$("#add input[type=submit]").click(function(){
newPost = $("#add textarea").val();
$.ajax({
type : "POST",
url : "/add",
data : { "post" : newPost },
success: function(data) {
$('#posts ul').prepend('<li id="1234"><p>'+newPost+'<p><span class="delete">Delete</span></li>');
}
});
这按预期工作,但正如您所看到的,我为每个帖子都有一个“删除”按钮,并且我使用以下 jquery 删除帖子:
$(".delete").click(function(){
var thiscache = $(this),
post_id = thiscache.closest("li").find("p").attr("id");
$.ajax({
type : "POST",
url : "/delete",
data : { "post_id" : post_id },
success : function(r){
thiscache.parent().slideUp('slow');
},
});
});
删除将适用于之前添加的帖子,但如果您使用 ajax 表单添加帖子,然后单击“删除”,则不会触发任何操作。这可能是什么原因造成的?也许是新帖子<li>
不在 DOM 中?
我创建了一个没有 Ajax 函数的 JSfiddle。 http://jsfiddle.net/bhhgf 如果您添加新帖子,它将追加它,但您无法删除它。删除当前的帖子就可以了。
编辑:
我还将 jeditable 与自定义事件一起使用,但 .live() 不会触发新帖子。
$("p").editable('/edit/save', {event : 'edit_button'});
$(".edit").live('click', function(){
$(this).closest("li").find("p").trigger('edit_button');
});
最佳答案
您应该使用 jQuery live()功能。这会将处理程序应用于与给定选择器匹配的所有当前和 future 元素。因此,附加到文档的新元素将具有附加到 click
的处理程序。
$(".delete").live('click', function(){
var thiscache = $(this),
post_id = thiscache.closest("li").find("p").attr("id");
$.ajax({
type : "POST",
url : "/delete",
data : { "post_id" : post_id },
success : function(r) {
thiscache.parent().slideUp('slow');
},
});
});
或者,您可以在添加新元素时添加处理程序,例如:
var deleteHandler = function() {
var thiscache = $(this),
post_id = thiscache.closest("li").find("p").attr("id");
$.ajax({
type : "POST",
url : "/delete",
data : { "post_id" : post_id },
success : function(r) {
thiscache.parent().slideUp('slow');
},
});
});
$(".delete").click(deleteHandler);
$("#add input[type=submit]").click(function(){
newPost = $("#add textarea").val();
$.ajax({
type : "POST",
url : "/add",
data : { "post" : newPost },
success: function(data) {
el = $('#posts ul').prepend('<li id="1234"><p>'+newPost+'<p><span class="delete">Delete</span></li>');
el.find('.delete').click(deleteHandler);
});
});
此方法将在出现时有选择地添加处理程序。
关于jquery - 在新添加的项目上查找 li,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7054467/