使用jquery onclick函数添加和删除按钮上的类

Giu*_*ini 6 html javascript jquery twitter-bootstrap

我实际上正在使用带有引导程序的按钮组结构.现在,当我点击它时,我需要为每个按钮添加活动类.当我点击另一个按钮时,从中删除.

这是我的HTML结构,是这样的:

<body>
    <div id="header">
        <div class="logo">Prova<span class="sec-logo">toscana</span>15</div>
        <div class="bottoni">
            <div class="btn-group" role="group" aria-label="...">
                <button type="button" class="btn btn-default" id="b1">12345</button>
                <button type="button" class="btn btn-default" id="b2">12345</button>
                <button type="button" class="btn btn-default" id="b3">12345</button>
                <button type="button" class="btn btn-default" id="b4">12345</button>
                <button type="button" class="btn btn-default" id="b5">12345</button>
                <button type="button" class="btn btn-default" id="b6">12345</button>
            </div>
        </div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?谢谢.

Mar*_*cin 5

如果在单击后.active不应从活动按钮中删除类,请使用addClass而不是toggelClass

$("#header .btn-group[role='group'] button").on('click', function(){
    $(this).siblings().removeClass('active')
    $(this).addClass('active');
})
Run Code Online (Sandbox Code Playgroud)

jsfiddle 示例

缩小按钮选择范围也是一种很好的做法,我使用了#headeid,.btn-group[role='group']这使得脚本仅应用于所有按钮组中的按钮 iside<div id="header"></div>

在这里你有.active类定义:

.btn.active{
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)