如何在jquery中设置class =“active”

时间:2011-12-19 08:57:09

标签: jquery

我有一个示例代码:

<div class="box">
        <div id="banks">
            <ul>
                <li class="active1">Bank1</li>
                <li">Bank2</li>
            </ul>
        </div>
        <div id="buttons">
            <ul>
                <li class="active2">USD</li>
                <li>EURO</li>
            </ul>        
        </div>
</div>

和jquery:

<script>
$(document).ready(function(){
    $('.box li').click(function(){
        $('#banks li').removeClass('active1');
        $('#buttons li').removeClass('active2');
        $(this).addClass('active1');
        $(this).addClass('active2');
    });    
});
</script>

OUPUT:点击时出错:

<div class="box">
        <div id="banks">
            <ul>
                <li class="active2 active1">Bank1</li>
                <li class="active2">Bank2</li>
            </ul>
        </div>
        <div id="buttons">
            <ul>
                <li class="">USD</li>
                <li class="">EURO</li>
            </ul>        
        </div>
</div>

如何使用jquery完全为2个id添加类是(银行和按钮)2类是(active1,active2)

4 个答案:

答案 0 :(得分:15)

据我了解,您需要能够在每个部分中选择单个选项。只使用一个active类并在css中更改样式:

HTML:

<div class="box">
        <div id="banks">
            <ul>
                <li class="active">Bank1</li>
                <li>Bank2</li>
            </ul>
        </div>
        <div id="buttons">
            <ul>
                <li class="active">USD</li>
                <li>EURO</li>
            </ul>        
        </div>
</div>

JS:

$(document).ready(function(){
    $('.box li').click(function() {
        $(this).siblings('li').removeClass('active');
        $(this).addClass('active');
    });
});

的CSS:

.box li { cursor:pointer; }
#banks .active { color:red; }
#buttons .active { color:blue; }

代码:http://jsfiddle.net/jn3v4/2/

答案 1 :(得分:1)

删除课程时,您只能在#box内部将其更改为.box

$('.box li').click(function(){
    $('.box li').removeClass('active1');
    $('.box li').removeClass('active2');
    $(this).addClass('active1');
    $(this).addClass('active2');
}); 

<强> DEMO

答案 2 :(得分:1)

&#13;
&#13;
$(document).ready(function(){
$(".active-class a").click(function() {
  $(".active-class a").removeClass("active");
  $(this).addClass("active");
});
});
&#13;
a.active
{
background:#000000;
color:#ffffff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
            <ul>
                <li class="active-class"><a href="#" class="active">home</a></li>
                <li class="active-class"><a href="#">about</a></li>
                <li class="active-class"><a href="#">gallery</a></li>
                <li class="active-class"><a href="#">contact us</a></li>
            </ul>
        </div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

Jquery函数:

(".box li").click(function() {
  $(".box li").removeClass('active');
  $(this).addClass('active');
});