如何为具有相同“for”属性的两个标签添加类?

时间:2015-12-24 22:14:38

标签: javascript jquery css

我有类似手风琴的东西,左侧标签导航,内部(内部雅致部分)标签,如“next / prev”。那么问题是如何检查attr“for”是否有两个相同的标签并为它们添加类?

input {
display: none;
}

input:checked + label {
color: red;
}

input + section {
display: none
}

input:checked + section {
display: block
}

label {
display: inline-block;
  border: 1px solid green;
  padding: 10px;
}
<label for="check">Label #1</label>
<label for="check2">Label #2</label>
<label for="check3">Label #3</label>
<label for="check4">Label #4</label>

<div>
<input type="radio" name="test" id="check"> 
<section>
Lorem ipsum dolor sit amet, vitae graeci vidisse et his, et vis quod appetere vulputate, eius verear habemus usu ne. Et usu senserit mediocrem imperdiet, habeo fugit paulo mel at. Velit minimum te qui. Sed te pertinacia eloquentiam, ad modus ponderum luptatum vel, vidisse accommodare id sit
<div><label for="check2">Next #2</label></div>
</section>
  
  <input type="radio" name="test" id="check2"> 
<section>
Lorem ipsum dolor sit amet, vitae graeci vidisse et his, et vis quod appetere vulputate, eius verear habemus usu ne. Et usu senserit mediocrem imperdiet, habeo fugit paulo mel at. Velit minimum te qui. Sed te pertinacia eloquentiam, ad modus ponderum luptatum vel, vidisse accommodare id sit

  <div><label for="check">Prev #1</label>
  <label for="check3">Next #3</label>
    </div>
</section>
  
  <input type="radio" name="test" id="check3"> 
<section>
Mel no erat platonem. Ius ad veritus minimum molestiae, ea blandit adolescens vix. Impetus epicuri ocurreret usu in, id aeterno fastidii molestiae his. Eruditi nonumes vel cu, has feugait ancillae efficiendi ex, cu vel augue tacimates. Augue mnesarchum et mei.

  <div><label for="check3">Prev #3</label> <label for="check4">Next #4</label></div>
</section>
  
  <input type="radio" name="test" id="check4"> 
<section>
Odio facilisis persequeris eu sed, in sea oblique labores. Ei vel utamur menandri, paulo omnium delectus vix id. Pri choro impetus persecuti eu. Est id illud luptatum dissentiunt. Vim id nemore aliquip, sea eligendi deseruisse ea. Quot elitr et has, deleniti oportere et nec, an molestiae adipiscing eos.
<div><label for="check3">Prev #3</label><label for="check">Next #1</label></div>
</section>



</div>

1 个答案:

答案 0 :(得分:2)

只需选择具有相同输入ID的所有标签,然后添加您的课程:

var id = "check",
    label = $('label[for="' + id + '"]');

label.addClass('your-class');

这将对您有所帮助:

$('.btn-lbl').click(function() {
    var id = $(this).attr('for');
    $('.how-it-works--label[for="' + id + '"]').addClass('active');
});