如何使用 jquery 将选中无线电的 data-* 属性设置为另一个元素的 class?

How to set data-* attribute of checked radio to class of another element using jquery?

如何将选中的单选按钮的 data-attribute 输出到不同元素的 class 属性中?

请看例子:

body{
  background: #eee;
}  

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>

<div class="box"></div>
<div class="box"></div>

您只能使用 CSS 来完成。 :checked select checked radio and ~ is General sibling selectors.

input[data-color="black"]:checked ~ .box {
    background: #000;
}

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

input[data-color="black"]:checked ~ .box {
  background: #000;
}

input[data-color="white"]:checked ~ .box {
  background: #fff;
}

input[data-color="green"]:checked ~ .box {
  background: #00d300;
}
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>

<div class="box"></div>

如果您想使用 jquery 执行此操作,您需要使用 .attr() or .data() and set it to class of .box using .addClass().

获取 data-color 属性的值
$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});

$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});
.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>
<div class="box"></div>