为多个元素提供唯一的类

时间:2015-11-12 12:55:52

标签: javascript jquery html

我有一堆span元素,我想给他们独特的类。像一,二,三四。然后重复下一个具有相同类的容器。它有可能与jQuery / vanilla js?或者说,我该怎么做?

我的HTML:

<div class="ccbnOutline">
    <span></span> -- give class one
    <span></span> -- give class two
    <span></span> -- give class three
    <span></span> -- give class four
</div>

<div class="ccbnOutline">
    <span></span> -- give class one
    <span></span> -- give class two
    <span></span> -- give class three
    <span></span> -- give class four
</div>

2 个答案:

答案 0 :(得分:2)

尝试:

var arr=["one","two","three","four"];
        $('.ccbOutline').each(function(ix,val) {
               val.find('span').each(function(i,v){
          $(this).addClass(arr[i]);
        });
    });

答案 1 :(得分:0)

你需要像这样的映射数组

var arr=["one","two","three","four"]; // "five","six " and so an
$('.ccbOutline  span').each(function(i){
  $(this).addClass(arr[i]);
});