Add class and remove class based on checked radio? [duplicate]

 ̄綄美尐妖づ 提交于 2019-12-13 06:27:39

问题


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



来源:https://stackoverflow.com/questions/17368753/add-class-and-remove-class-based-on-checked-radio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!