问题
Summed up answer
If you come across something similar here is the simple answer:
In my code I get the .val() value of the :checked radio input, that gets the value of all the radios that have been checked, this results in unwanted classes. Taking advantage of the .click callback we can get the .val() value of just the specific input value of the clicked item, which is a radio label in my case.
Here is another great solution to the problem I had.. Add class and remove class based on checked radio? and the jsbin to this solution http://jsbin.com/ugufi/27/
Hope this helps anyone else who may have the same issue... Pretty simple answer.. thanks to all!
The Question
Here is the code I have
http://jsbin.com/ugufi/11/
What I am struggling with is finding a solution to removing the class after adding it to the target.
I have a list of radio buttons, I am getting the value of the :checked radio input and putting that value in a class.
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 -->
PS. Ive looked this question up and found many answers but they all use some sort of .siblings() or .parent() callback, they are great solutions, but the inputs and the target are distant from eachother in my code.
回答1:
Changing my answer to be more complete:
$('.moon-generator-attr').click(function() {
var tabid = $(this).val();
$('.icon-wrap a.icon').attr('class','icon icon-'+tabid);
alert($('.icon-wrap a.icon').attr('class'));
});
This will make the class icon and whatever second class you'd like. That way you can still access the element with $('.icon-wrap .icon')
You could also do this if you only have one "a" in your .icon-wrap div:
$('.moon-generator-attr').click(function() {
var tabid = $(this).val();
$('.icon-wrap a').attr('class','icon-'+tabid);
alert($('.icon-wrap a').attr('class'));
});
回答2:
Remove old class + add a new class
$(this).removeClass().addClass('icon-'+tabid+'');
Full code:
$('.moon-generator-attr').click(function() {
var tabid = $('.moon-generator-attr:checked').val();
$(this).removeClass().addClass('icon-'+tabid+'');
alert($('.icon-wrap a.icon').attr("class"));
});
来源:https://stackoverflow.com/questions/17367683/add-class-to-target-based-on-radio-input-value-toggle-like-function