我附加从 Ajax 接收的数据,它还包含一个带有类 bsubmit 的除法。当页面加载时,如果我单击包含类 bsubit 的div,则执行以下函数,但是当我单击还包含类 bsubmit 的新附加数据时,下面的代码不起作用。
这是代码
$(function() {
$(".bsubmit").click(function() {
var id = $(this).parent().parent().attr("id");
var comm= document.getElementById(id).getElementsByClassName("commentadd")[0].value;
$.ajax({
type: "POST",
url: "comment.php",
data: {id:id, comm:comm},
cache: false,
success: function(data){
$('.addcomment').slideUp('slow', function() {
});
// Bottom Line not working
$("#"+id).find(".item_comment").append(data); // DATA Contains a div with class bsubmit
$(data).appendTo("#"+id).find(".item_comment"); // Now these Appended Div isnt calling this function again, Why ? I want to call them again
$('#load').fadeOut();
}
});
return false;
});
});
如果我理解你的问题:你尝试过.on()
方法吗?(jQuery 1.7)
$(yourParentElement).on('click','.bsubmit',function() {
您的问题是您将 click 事件绑定到 .bsubmit
类,但该 click 事件仅受到文档中已有.bsubmit
的攻击,而不是新创建的。
所以,你需要做的是,根据你的Jquery版本使用live()或on()。
更改此行:
$(".bsubmit").click(function() {
自
Jquery LIVE
$(".bsubmit").live("click", function() {
或
Jquery ON
$(".bsubmit").on("click", function() {
appendTo
不返回父级。
$("#"+id).find(".item_comment").append(data);
$(data).appendTo("#"+id).parent().find(".item_comment"); // Use "parent()"
$('#load').fadeOut();
但是你真的应该缓存一些 DOM 元素......
var id = $(this).parent().parent().attr("id");
更改为:
var $parent = $(this).parent().parent();
然后:
$("#"+id).find(".item_comment").append(data);
更改为:
$parent.find(".item_comment").append(data);