简体   繁体   中英

Select dynamically added li in Jquery

I am appending li in a Ul dynamically with a rel attribute. Now I need to select the last li and it's attributes. But it is unable to select the dynamically added li.

  var lastRel = $("#ulid li:last").attr("rel");


$("#addLi").on('click', function(){
$("ul").append('<li rel="5">5</li>');
});


$("#getLast").on('click', function(){
alert(lastRel);
});

Check this Fiddle..

FIDDLE

You need to put the code where you get the last reference of li in the button click:

$("#getLast").on('click', function(){
    var lastRel = $("#ulid li:last").attr("rel");
    alert(lastRel);
});

This is because when you originally set your variable, it is at page load when there are only 4 li 's.

You need to set the variable again when you have updated the last li .

 $("#addLi").on('click', function(){ $("ul").append('<li rel="5">5</li>'); }); $("#getLast").on('click', function(){ var lastRel = $("#ulid li:last").attr("rel"); alert(lastRel); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="ulid"> <li rel="1">1</li> <li rel="2">2</li> <li rel="3">3</li> <li rel="4">4</li> </ul> <input type="button" id="addLi" name="addLi" value="Add Li"> <input type="button" id="getLast" name="getLast" value="Read Last LI"> 

You need to update your lastRel after adding a new <li>

$("#addLi").on('click', function(){
    $("ul").append('<li rel="5">5</li>');
    lastRel = $("#ulid li:last").attr("rel");
});

$("#getLast").on('click', function(){
    alert(lastRel);
});

FIDDLE

Everything you have done was right you have misplaced this code

var lastRel = $("#ulid li:last").attr("rel");

This piece of code should come inside your click event.

But i suggest you to have Id dynamically for the li also. So you can directly access the selector.

Example:

<li id="name-1"></li>
<li id="name-2"></li>

So in my jQuery I can do something like this

$("#name-"+id).val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM