使用复选框,我想更改两个单选按钮的选中状态。这工作正常,但是当再次更改复选框时,单选按钮选中的视觉效果“消失”,而代码显示它已选中。这是怎么来的?
JS:
$("#change_radio").change(function () {
if ($(this).is(":checked")) {
$("#one").attr("checked", false);
$("#two").attr("checked", "checked");
}
else {
$("#two").attr("checked", false);
$("#one").attr("checked", "checked");
}
});
HTML:
<input type="radio" id="one" name="test" checked="checked"><label for="one">one</label>
<input type="radio" id="two" name="test"> <label for="two">two</label>
<input type="checkbox" id="change_radio"> <label for="change_radio">check</label>
最佳答案
更改你的 JavaScript 并使用 prop 而不是 attr
$("#change_radio").change(function () {
console.log("change");
if ($(this).is(":checked")) {
$("#one").attr("checked", false);
$("#two").prop('checked', true);
}
else {
$("#two").attr("checked", false);
$("#one").prop('checked', true);
}
});
使用
$("#one").prop('checked', true);
而不是
$("#one").attr('已检查', '已检查');
享受吧:)
关于javascript - 单选按钮 'disappearing',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656729/