将样式应用于选中的单选按钮'

Applying styling to a checked radio button's parent

本文关键字:单选按钮 样式 应用于      更新时间:2023-09-26

所以我在<li>元素中有一系列单选按钮。我试图创建一个边界上说<li>只有当它的子单选按钮被选中。

我在jQuery中有一个折衷的解决方案:

$('input[type="radio"]').change(function() {
    if($(this).is(':checked')) 
    { 
        $(this).parent().css('border', '1px solid black');
    } 
    else 
    {
        $(this).parent().css('border', 'none');
    }
});

但是,这只会添加样式,而不会在选择单选按钮中的不同选项时删除它。所以,如果你点击了所有的选项,它们最终都应用了样式。

我能做什么?

当单选按钮被更改时,您必须删除其他LI元素的样式

var lis = $('input[type="radio"]').change(function() {
    lis.css('border', 'none');
    if ($(this).is(':checked') ) { 
        $(this).parent().css('border', '1px solid black');
    } 
}).parent(); // gets all the parents
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><input type="radio" name="group"></li>
    <li><input type="radio" name="group"></li>
    <li><input type="radio" name="group"></li>
</ul>