HTML:
<div class="main">
<div class="inputs">
<input type="radio" name="rb" class="rb_1">
<input type="radio" name="rb" class="rb_2">
<input type="radio" name="rb" class="rb_3">
</div>
</div>
现在我想将所选输入字段的类添加到main元素中。这意味着如果我选择第二个无线电场,结果应为:
反之亦然:如果main元素有一个.rb _ * - 类,则应选择无线电字段:如果.main有类&#39; rb_3&#39; - &GT;应选择第三个无线电场
JS:
// First question
$(".main").each(function () {
var rb = $(this).children("input[type='radio']:checked").attr('class');
if (rb) { $(this).addClass(rb);
});
/second question
$(".main").each(function () {
if ($(this).hasClass(".rb_*")) {
// get class value for var rb = ...
$(this).children(rb).prop('checked', true);
}
});
答案 0 :(得分:1)
//check if main div has specific class & check the respective radio
$("input[class^='rb_']").each(function() {
var rad = $(this),
clname = rad.attr('class');
//check if 'main' div has class as in checked radio
if($("div.main").hasClass(clname)) {
rad.prop('checked', true);
}
});
和
$("input[name='rb']").on("change", function() {
var selected = $(this).prop('checked'),
mainEle = $("div.main"),
classNaam = $(this).attr('class');
//remove all class from element
mainEle[0].className = '';
if(selected) {
//add 'main' and class from checked radio
mainEle.addClass('main ' + classNaam);
}
else {
//add only 'main' class
mainEle.addClass('main');
}
});