开发者

Add Different Style to list tag using jquery/javascript

Is there any ways to add different style class to all li in a ul tag using jquery/javascript/php. Consider I have a list as follows

<ul><li>a</li><l开发者_开发技巧i>b</li><li>c</li><li>d</li><li>e</li></ul>

I would like to add as follows

<ul><li class='cat1'>a</li><li class='cat2'>b</li><li class='cat3'>c</li><li class='cat4'>d</li><li class='cat5'>e</li></ul>


As simple as:

$('ul').children('li').addClass(function (i) {
    return 'cat' + (i+1);
});

http://api.jquery.com/addClass/


If you want to set the class, the cheaper way to do it is by using .attr() and the index in its setter function, like this:

$("ul li").attr("class", function(i) {
  return "cat" + (i+1);
});

If you aren't setting it and just adding, use .addClass(function(i) instead of .attr("class", function(i).


$('ul').children('li').each(function(i,v){
   $(this).addClass('cat'+(i+1));
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜