如何在单选按钮上添加和删除类

How to add and remove class on radio button?

本文关键字:删除 添加 单选按钮      更新时间:2023-09-26

当我在JSFiddle上找到这个时,我遇到了问题

http://fiddle.jshell.net/pepesustaita/sdL2v/

有两个收音机用于采样,但我需要更多的无线电…

 $(document).ready(function(){
    $('#radio1').click(function(){
        $('.what1').addClass('active1').siblings().removeClass('active');       
    });
    $('#radio2').click(function(){
        $('.what2').addClass('active').siblings().removeClass('active1');       
    });
});

如何为第3、第4等添加更多条件。div ?

如果我理解正确,您正在寻找一个更通用的解决方案,而不是为每个元素分配单个单击处理程序?或许,可以这样写:

$(document).ready(function(){
    $('input[type="radio"]').click(function( ){
        $('input[type="radio"]').siblings().removeClass('active');
        $(this).next().next().addClass('active');
    });
});

这将为radio类型的每个输入附加相同的click处理程序。当一个单选按钮被单击时,活动类被从所有其他单选按钮中删除,然后活动类被添加到最后一个被单击的单选按钮中。

小提琴:http://fiddle.jshell.net/adrv14of/

首先为输入设置一个类,然后在Mousedown和MouseUp事件中编写以下代码:

$(document).on("mousedown",
            ".radio-type-input",
            function(ev) {
                $(".radio-type-input").removeClass("active");
            });
        $(document).on("mouseup",
            ".radio-type-input",
            function(ev) {
                $(ev.target).addClass("active");
            });