2012-05-18 99 views
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>"); 
     }); 
    }); 
}); 

但它沒有這樣做anything.I不知道,如果

var thisID = this.id; 

工作與否。我改變了一下我的代碼: $(function(){ $('.text').bind('click',function(){ alert("Hello!") }); });

還是什麼都沒有發生!!我懷疑函數中是否選擇了.text。任何人都可以幫忙?謝謝!

回答

2

你應該閱讀有關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  
}); 
+0

謝謝!我照你說的做了。但控制檯說:Uncaught TypeError:對象#沒有方法'on'。我確實將jquery包含爲。那麼爲什麼會發生? –

+0

@餘俊武嗯..它應該存在於1.7中。你把你的鱈魚包裝在'.ready()'中嗎?如果您使用其他框架,請嘗試使用'jQuery'而不是'$'。 – Joseph

+0

得到它的工作!!我以某種方式在1.7.2之後包含一箇舊版本庫,這就是爲什麼錯誤來了! –

0

使用.live()而不是.bind()。然後,它會對網頁上出現的新元素保持警惕。

其實醫生說:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

+1

'.live()'已棄用。使用'.on()'的特殊語法。 – Blender