javascript - 将样式应用于选中的单选按钮的父级

标签 javascript jquery html css

所以我里面有一系列的单选按钮<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>

关于javascript - 将样式应用于选中的单选按钮的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245293/

相关文章:

html - hpricot 将属性添加到 HTML 标记?

php - 在 HTML 表格中每 n 个单元格创建一个新行

javascript - 通过 CSS3 和 Jquery 处理视差

javascript - 谁在传递参数来替换函数?

javascript - Accordion 高度问题

javascript - jQuery slider 建议

javascript - jQuery .css() 附加或覆盖

javascript - 出错时显示div

javascript - 可以使浏览器不删除字符

javascript - Facebook API FB.getLoginStatus 返回未定义