选择链接以添加类选择

时间:2014-01-08 09:51:02

标签: jquery addclass

好吧,我有一个问题是添加一个选择的类名这是我的HTML代码:

<div class="module">
    <ul class="accordion">
        <li><a class="element" href="#about">About</a></li>
        <li><a class="element" href="#services">Services</a></li>
        <li><a class="element" href="#areas" >Areas</a></li>
    </ul>
    <div class="heading" id="about">
        ...
    </div>
    <div class="heading" id="services">
        ...
    </div>
    <div class="heading" id="areas">
        ...
    </div>
    <div style="clear: both; display: none;"></div>
</div>

我的CSS代码

ul.accordion-btn li{list-style:none;float:left;padding:5px 10px;margin:0 1px 0;text-transform:uppercase;box-shadow:0px 2px 2px 0px rgba(0,0,0,0.3);}
ul.accordion-btn li{background:#fafaf9;}
.module h1{font-size:1.8em; font-weight:normal;}
.module{padding:0;margin:10px 0;}
ul.accordion-btn{display:table;}
ul.accordion-btn a{color:#1E587F;margin:0;}
.heading{display:block;float:left;width:660px;min-height:320px;}
.selected{color:#FFF;text-decoration:none;border-color:#1E587F;background-color: Yellow;}

所以我正在使用一些jquery,需要一些帮助

var tabContainers = $('div.module > div');
jQuery('.accordion').addClass('accordion-btn');
$('div.module ul.accordion a').click(function(){
    tabContainers.hide().filter(this.hash).fadeIn('fast');
    tabContainers.removeClass('selected');
    $(this).addClass('selected');
}).filter(':first').click();

3 个答案:

答案 0 :(得分:1)

看起来您要将div定位为添加类 - 因为您要从tabContainers

中删除该类
var tabContainers = $('div.module > div');
jQuery('.accordion').addClass('accordion-btn');
$('div.module ul.accordion a').click(function () {
    tabContainers.hide().removeClass('selected');
    $(this.hash).fadeIn('fast').addClass('selected');
}).filter(':first').click();

演示:Fiddle

答案 1 :(得分:0)

试试这个,

var tabContainers = $('div.heading');
jQuery('.accordion').addClass('accordion-btn');
$('div.module ul.accordion a').click(function(e){
    e.preventDefault();
    tabContainers.removeClass('selected').hide();
    $(this.hash).fadeIn('fast')
                .addClass('selected');
}).filter(':first').click();

Demo

如果您想add class anchor,请尝试此操作,

$('div.module ul.accordion a').click(function(e){
    e.preventDefault();
    tabContainers.removeClass('selected').hide();
    $(this.hash).fadeIn('fast');
    $(' ul.accordion a').removeClass('selected');// remove class from all active anchor
    $(this).addClass('selected');// make it selected/active
}).filter(':first').click();

Updated Demo

答案 2 :(得分:0)

$(document).ready(function(){<br>
var tabContainers = $('div.module > div');<br>
jQuery('.accordion').addClass('accordion-btn');<br>
$('div.module ul.accordion a').click(function () {<br>
    $('div.module ul.accordion a').removeClass('selected');<br>
    tabContainers.hide();<br>
    $(this).addClass('selected');<br>
    $(this.hash).fadeIn('fast').addClass('selected');<br>
}).filter(':first').click();<br>
})