2015-02-12 30 views
1

我想要獲得附加列表元素的ID。在嘗試了幾個小時並從jquery get the id/value of LI after click functionHow to get the id of html list item using jquery?中讀取多個源文件後,我仍然無法弄清楚我的代碼中的錯誤。查找附加(通過函數)html列表元素與jQuery的ID

上面的來源和我想要實現的唯一區別是他們已經有列表元素存在於html裏面,因爲我通過jquery函數追加列表。

這是我的代碼。

的Html

<button id="display">Display</button> 
<div class="main"> 
    <ul> 
    </ul> 
</div> 
<p id="show"> </p> 

jQuery的2.1.0

var i = 1; 
$('#display').click(function() { 
    $(".main ul").append(
     $('<li>').attr("id",i).append(
      $('<p>').append("Stackoverflow") 
      )); 
    i++; 
}); 


$('.main ul li').click(function() { 
    $('#show').text("List ID =" + this.id);  
}); 

jsfiddle

謝謝您的時間。

+0

使用'$( 「主UL 」)。在(「 點擊」, 「li」,function()...);' – Barmar 2015-02-12 02:26:09

+0

請參閱http://jsfiddle.net/mtg39cd5/1/ – Barmar 2015-02-12 02:26:58

+0

感謝您的快速回復Barmar現在正在工作,我將檢查on()的文檔,但是您能否很快解釋爲什麼click沒有成功,但是.on做到了。 – 2015-02-12 02:36:32

回答

1

嘗試從

$('.main ul li').click(function() { 

改變

$('.main').on('click', 'ul li', function() { 

FIDDLE