无法选择 ajax 注入的元素



我编写了代码以使用 ajax 更新帖子:

 $(function(){
   $('#loadFeed').bind('click',function(){ 
        $.getJSON('getData.php', function(json) {
            var output="<ul id='feedsList'>";
            for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
                output+="<li class='post'>";
                output+="<div class='text'>"+json.posts[i].shortmsg+"</div>";         
                output+="</li>";
            }
            output+="</ul>"
            $(output).appendTo('.posts');
    });
  });
});

我的网页代码:

<div data-role="content" class="ui-content" role="main">
        <div class="posts"></div>
 </div>

然后我想点击每个帖子,帖子会展开以显示更详细的内容。我该怎么做?我写的代码是:

$(function(){
     $('.text').bind('click',function(){
         $.getJSON('getData.php', function(json){   
         var thisID = this.id;      
         $(this).replaceWith("<div class='long_text'>"+json.posts[thisID].msg+"<div>"); 
         });
     });
});

但它什么也没做。我不确定是否

var thisID = this.id;

工作与否。我稍微更改了一下代码: $(function(){ $('.text').bind('click',function(){ alert("Hello!") }); });

还是什么都没发生!!我怀疑是否在函数中选择了 .text。有人可以帮忙吗?谢谢!

你应该

阅读jQuery的.on()

假设您有一个在动态内容之前存在的容器,

<div class="posts">
    <!--dynamic content here-->
</div>

然后,将处理程序附加到现有容器一次,它将侦听动态内容的事件

//"add listener for .text, attached on .post"
$('.posts').on('click','.text', function(){
    //do stuff when text is clicked    
});
使用 .

live(( 而不是 .bind((。然后,它将对页面上出现的新元素保持警惕。

实际上文档 说:

从jQuery 1.7开始,.live((方法已被弃用。使用 .on(( 来 附加事件处理程序。旧版本的jQuery的用户应该使用 .delegate(( 优先于 .live((。

最新更新