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");
精彩评论