2010-03-18 70 views
1

我有一個無序的鏈接列表,這些鏈接是由Ajax動態創建的,並且我想爲每個鏈接添加點擊功能,但它不起作用,請幫忙!如何在jquery中訪問動態創建的列表?

這裏是我的代碼:

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()); 
}); 
+0

您知道您的HTML無效嗎? 'li'元素必須被'ul'或'ol'包圍。 – 2010-03-18 00:22:09

回答

1

應該是.click()而不是.each()

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

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

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

謝謝,.live()做到了! – Ohana 2010-03-18 00:38:19

0

也許你需要.live()

德cription:爲現在或將來與當前選擇器匹配的所有元素附加事件處理程序。

0

我一直在爲這一整天而戰!

.live()是我所需要的。

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