开发者

how do i get the last element of a $.each

i have this

     $.each(data, function (url) {
      $("ul"开发者_Python百科).append($("<li class='horizontal'></li>").html(this.title));
    });

I want to add the class last to the last one...how would i do that


$.each(data, function(i,v){
  $('<li />').html(v.title).appendTo('ul');
});
$('ul li:last').addClass('horizontal');

jsFiddle


Do you mean to the UL or LI? Just do (after the loop):

$("#theUl li:last").addClass("horizontal"); // or $("ul:last"), whichever you mean

You can do it within the loop, but I would not suggest it, as it will require a check at each iteration.

For better overall performance, you can reduce the number of writes to the DOM by building up the LIs offline and appending them in one go:

var lis = '';
$.each(data, function (url) {
    lis += "<li>" + this.title + "</li>";
});
$("ul").append(lis);
$("ul li:last").addClass("horizontal");


If data is an array, you could do

data.length

and it'll give you the quantity. Then, one could carry a counter inside the .each and check if you got to the last element.

Something like that... but there should be a last selector in jquery.


 $.each(data, function (url) {
  $("ul").append($("<li class='horizontal'></li>").html(this.title));
});

$("ul li:last").addClass("last");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜