简体   繁体   English

在Jquery中分配类的所有元素唯一ID

[英]Assigning all elements of a class unique IDs in Jquery

So I have a group of labels that all belong to the "btn btn-warning" bootstrap class: 因此,我有一组标签都属于“ btn btn-warning”引导程序类:

<div class = "btn-group" data-toggle = "buttons">
  <label class="btn btn-warning active">
    <input type="radio" checked>QA 71</input>
  </label>
  <label class="btn btn-warning">
    <input type="radio">QA 72</input>
  </label>
  <label class="btn btn-warning">
    <input type="radio">QA 73</input>
  </label>
  <label class="btn btn-warning">
    <input type="radio">QA 74</input>
  </label>
  <label class="btn btn-warning">
    <input type="radio">ST 71</input>
  </label>
  <label class="btn btn-warning">
    <input type="radio">PR/Beta</input>
  </label>
</div>

I would like to assign IDs to all of them, with the one labeled QA 71 as environment1 , the next one as environment2 , etc. Here is my jquery function: 我想的ID分配给所有的人,用标记QA 71作为一个environment1 ,下一个为environment2 ,等等。这里是我的jQuery函数:

var count = 1;
var btnid = "";
$(document).ready(function(){
  $("label .btn-warning").each(
    function(){                     
      btnid = "environment"+count;
      $(this).attr("id", btnid);
      count++;
    });
});

However, this is not working. 但是,这不起作用。 What am I doing wrong? 我究竟做错了什么?

The reason it doesn't work, is because the selector is wrong, a label with a class is denoted as label.classname 之所以不起作用,是因为选择器错误,带有类的标签表示为label.classname

jQuery's each() also already has a count in the first argument, use that jQuery的each()在第一个参数中也已经有一个计数,请使用

$(document).ready(function(){
    $("label.btn-warning").each(function(index, elem){                     
        elem.id = "environment" + (index + 1); // zero based
    });
});

You could even use attr() with a callback 您甚至可以将attr()与回调一起使用

$(document).ready(function(){
    $("label.btn-warning").attr('id', function(index){                     
        return "environment" + (index + 1); // zero based
    });
});

There is a space between label and btn-warning which mean it will try to look for a class inside label, which is not the case . labelbtn-warning之间有一个空格,这意味着它将尝试在label内部查找一个类,事实并非如此。

$("label.btn-warning")

JSFIDDLE JSFIDDLE

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

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