簡體   English   中英

如何訪問jQuery中動態創建的列表?

[英]how to access dynamically created list in jquery?

我有一個無序的鏈接列表,這些鏈接是由Ajax動態創建的,對於每個鏈接,我都想向其中添加單擊功能,但是它不起作用,請幫忙!

這是我的代碼:

HTML

<div id="sidebar">
  <li>
      <h2> list </h2>
      <ul id="list"></ul>
  </li>
</div>

JS

//to create links
var str = '';
$.each(json.opts, function(i, opt) {
  var id = opt + '-list';
  str += '<li><a href="#" id='+ id +'>' + opt + '</a></li>';   //link
}
$("#list").html(str);

...
//to add click function to each links, this won't work
$("#list li").each(function (i) {
   alert(i + " : " + $(this).text());
});

.click()代替.each()

$("#list li").click(function (i) {
   alert(i + " : " + $(this).text());
});

而且,如果調用此函數,則必須已經插入元素。 否則,您必須使用.live()

$("#list li").live('click', function (i) {
   alert(i + " : " + $(this).text());
});

也許你需要.live()

說明:為現在或將來與當前選擇器匹配的所有元素的事件添加處理程序。

我整天都在戰斗!

.live()是我需要的。

我已經動態創建了未響應.click()的幻燈片編號鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM