0

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');
    });
  });
});

私のhtmlコード:

<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 が選択されているかどうか疑問に思いました。

4

2 に答える 2

2

jQueryについて読む必要があります.on()

動的コンテンツの前にコンテナが存在するとします。

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

次に、ハンドラーを既存のコンテナーに1 回アタッチすると、動的コンテンツのイベントをリッスンします。 

//"add listener for .text, attached on .post"
$('.posts').on('click','.text', function(){
    //do stuff when text is clicked    
});
于 2012-05-18T05:46:27.230 に答える
0

.bind() の代わりに .live() を使用してください。その後、ページに新しい要素が表示されるのを警戒します。

実際、ドキュメントは次のように述べています。

jQuery 1.7 以降、.live() メソッドは非推奨になりました。.on() を使用して、イベント ハンドラーをアタッチします。古いバージョンの jQuery のユーザーは、.live() よりも .delegate() を使用する必要があります。

于 2012-05-18T05:44:40.253 に答える