这是我无法弄清楚如何使jquery读取单选按钮的值,然后转换为将更改文本颜色的函数的代码。

代码:https://jsfiddle.net/RhnvU/3898/

HTML:

<span id="quotechange"> HEllloooooo </span>

<div id="mydiv">
                Color:
                    <label class="color1"><input type="radio"  name="color" value="color1" checked="checked">Black</label>
                    <label class="color2"><input type="radio"  name="color" value="color2" >Purple</label>
                    <label class="color3"><input type="radio"  name="color" value="color3" >Orange</label>
                    <label class="color4"><input type="radio"  name="color" value="color4" >Red</label> <br>

                Style:
                    <label class="stylebold"><input type="checkbox" name="style1" value="stylebold" > Bold</label>
                    <label class="styleitalic"><input type="checkbox" name="style2" value="styleitalic" > Italic</label>
           </div>


CSS:

.color1 {
    color: black;
}
.color2 {
    color: purple;
}
.color3 {
    color: orange;
}
.color4 {
    color: red;
}


JS:

$('#mydiv input').click(colorClick($('input[name=color]:checked', '#mydiv').val()));


function colorClick(color) {
    if(color == "color1") {
        $("#quotechange").removeClass("color2");
        $("#quotechange").removeClass("color3");
        $("#quotechange").removeClass("color4");
        $("#quotechange").addClass("color1");
    }
    else if(color == "color2"){
        $("#quotechange").removeClass("color1");
        $("#quotechange").removeClass("color3");
        $("#quotechange").removeClass("color4");
        $("#quotechange").addClass("color2");
    }
    else if(color == "color3"){
        $("#quotechange").removeClass("color1");
        $("#quotechange").removeClass("color2");
        $("#quotechange").removeClass("color4");
        $("#quotechange").addClass("color3");
    }
    else if(color == "color4"){
        $("#quotechange").removeClass("color1");
        $("#quotechange").removeClass("color3");
        $("#quotechange").removeClass("color2");
        $("#quotechange").addClass("color4");
    }
}

最佳答案

您可以简单地使用$(this).val()

$('#mydiv input:radio').on('change', function() {
    $('#test').attr('class', '').addClass($(this).val());
});


$('#mydiv input:checkbox').on('change', function() {
    $('#test').addClass($(this).val());
    //or if you use this, it will take care when unchecked
    //$('#test').toggleClass($(this).val());
});


演示:https://jsfiddle.net/erkaner/RhnvU/3908/

更新资料

已解决的问题:When bold and/or italic are checked and a new color is picked the bold and italic remain checked but the value gets reset for them

演示:https://jsfiddle.net/erkaner/RhnvU/3910/

$('#mydiv input:radio').on('change', function () {
    var checkedboxes = $('#mydiv input:checkbox:checked').map(function(){
      return $(this).val();
    }).get();

    $('#test').attr('class', checkedboxes.join(' ')).addClass($(this).val());
});

09-27 06:05