最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting value from li created dynamically - Stack Overflow

programmeradmin0浏览0评论

I want to get the value from a dynamically LI I created.

I found this answer which explains how to get it normally.

This is my code. This works perfect for the two elements I have on my LI.

<ul class="nav nav-pills nav-stacked" id="listPreReq" style="height: 200px; overflow: auto" role="menu">
  <li class="active"><a href="#">Action</a></li>
  <li><a href="#">Another action</a></li>
</ul>


$("#listPreReq li").click(function() {    
 alert($(this).html());  
});

But I have this option for adding more elements to the LI. All the new elements I added, they don't fire the $("#listPreReq li").click event. Not sure why. This is a demo.

$('#btPre').click(function(e) {
  var Psize= $("#listPreReq").find("li");
  Psize = Psize.size()+1;
  $("#listPreReq").append('<li><a href="#">Page '+Psize+'</a></li>');
});

I want to get the value from a dynamically LI I created.

I found this answer which explains how to get it normally.

This is my code. This works perfect for the two elements I have on my LI.

<ul class="nav nav-pills nav-stacked" id="listPreReq" style="height: 200px; overflow: auto" role="menu">
  <li class="active"><a href="#">Action</a></li>
  <li><a href="#">Another action</a></li>
</ul>


$("#listPreReq li").click(function() {    
 alert($(this).html());  
});

But I have this option for adding more elements to the LI. All the new elements I added, they don't fire the $("#listPreReq li").click event. Not sure why. This is a demo.

$('#btPre').click(function(e) {
  var Psize= $("#listPreReq").find("li");
  Psize = Psize.size()+1;
  $("#listPreReq").append('<li><a href="#">Page '+Psize+'</a></li>');
});
Share Improve this question edited May 23, 2017 at 10:32 CommunityBot 11 silver badge asked Jun 21, 2014 at 19:52 DiegoDiego 9641 gold badge14 silver badges40 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

Solution Demo

Instead of binding events to document you can even bind them to ul:

$("#listPreReq").on('click', 'li', function() {    
    alert($(this).html());  
});

Have a look at event delegation.

use $(document).on('click','#btPre',function(e) {... instead of $('#btPre').click(function(e) {... and it will be fired! it is called event delegation!

UPDATE: and also this part too:

$("#listPreReq li").click(function() {...

change it to:

$(document).on('click',"#listPreReq li",function() {...
发布评论

评论列表(0)

  1. 暂无评论