Add class and remove class based on checked radio?

2019-08-25 04:25发布

问题:

This question is an exact duplicate of:

  • Add class to target based on radio input value (toggle, like function) 2 answers

Here is my jsbin, http://jsbin.com/ugufi/11 I removed any attempt I made to remove the class, because it just kept alerting undefined.

My problem is when I add the checked class to my target I (as said above) fail to remove the class of the target.

I cannot use parent or sibling selectors, because the target is separate from my nested radio inputs.

When a new radio is checked It keeps adding onto the class ex

<div class="radio1 radio2 radio3 radio4"></div>

What I need (which I know is very simple but Im not sure what to use).

<div class="radio1"></div><!-- Radio input value with radio1 is checked -->

then when I check a new radio input

<div class="radio4"></div><!-- Radio input value with radio4 is checked -->

回答1:

That's not true, you can use siblings method, your element doesn't have to be a very next sibling of the selected element. By using addClass you should remove previously added classes, you can either remove those classes using removeClass method or overwrite the class attribute/property by setting a new value:

$('.moon-generator-attr').change(function() {
   var $this = $(this);  
   $this.siblings('.icon-wrap').find('a').attr('class', function(){
      return 'icon icon-' + $this.val();
   });
});

http://jsbin.com/ugufi/22