gpt4 book ai didi

javascript - 如何将类添加到单选按钮组中未单击的单选按钮

转载 作者:太空宇宙 更新时间:2023-11-03 22:15:26 24 4
gpt4 key购买 nike

我有一个如下所示的单选按钮组

<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="8" accessory="14" img="/male/C8A14">
<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="9" accessory="15" img="/male/C9A15">
<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="10" accessory="16" img="/male/C10A16">

等等..

当我使用 JQuery 单击按钮时,我需要添加一个 CSS 类到未单击的单选按钮。

下面的代码没有按预期工作,它在点击时添加了一个类。

$('.radiowear').click(function() {
if ($('input:radio[name=wear_radio]').not(":checked")) {
$(this).addClass('low-up');
} else {
$(this).removeClass('low-up');
}
console.log(this.getAttribute('class'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="8" accessory="14" img="/male/C8A14">
<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="9" accessory="15" img="/male/C9A15">
<input type="radio" class="radiowear" name="wear_radio" shoe="" cloth="10" accessory="16" img="/male/C10A16">

更好的方法是什么?谢谢。

最佳答案

只需更改所有类并删除此类 - 我必须用标签包装才能看到类的任何更改。如果您想更改 radio 上的类,请删除 .parent()

我为 checked 添加了一个测试,这样我就可以在已经检查过的情况下触发 change onload

const $wearradios =  $('.radiowear');
$wearradios.on("change",function(e) {
$wearradios.parent().addClass("low-up");
$(this).parent().toggleClass("low-up",!this.checked)
}).change();
.low-up { background-color:red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="radiowear"
name="wear_radio" data-shoe="" data-cloth="8" data-accessory="14" data-img="/male/C8A14"></label>
<label><input type="radio" class="radiowear"
name="wear_radio" data-shoe="" data-cloth="9" data-accessory="15" data-img="/male/C9A15"></label>
<label><input type="radio" class="radiowear"
name="wear_radio" data-shoe="" data-cloth="10" data-accessory="16" data-img="/male/C10A16"></label>

关于javascript - 如何将类添加到单选按钮组中未单击的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57095135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com