简体   繁体   English

使用jquery / javascript将不同的样式添加到列表标记

[英]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. 有没有办法使用jquery / javascript / php为ul标签中的所有li添加不同的样式类。 Consider I have a list as follows 考虑我有一个列表如下

<ul><li>a</li><li>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/ 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: 如果你想设置类,更便宜的方法是使用.attr()和其setter函数中的索引,如下所示:

$("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) . 如果你没有设置它并且只是添加 ,请使用.addClass(function(i)而不是.attr("class", function(i)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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