如何添加活动类显示/隐藏选项卡?

时间:2015-03-09 17:14:21

标签: jquery

我想要实现的是当我点击一个标签时,它会添加一个“活动”类,但它显示错误的内容。

所以div1显示div2内容而div2显示div1内容,我的代码如下:

<div class="buttons">
<a id="buttonshowone" class="showsearch active" target="1">Properties For Sale</a>
<a id="buttonshowtwo" class="showsearch" target="2">Properties To Let</a>
</div>
<div id="div1" class="searchbut">
</div>
<div id="div2" class="searchbut">
</div>

我的Jquery如下:

jQuery(function(){
    jQuery('#div1').show();
    jQuery('#div2').hide();
    jQuery('.showsearch').click(function(){
        jQuery('.searchbut').hide();
        jQuery('#div'+$(this).addClass('active').siblings().removeClass('active').attr('target')).show();
    });
});

2 个答案:

答案 0 :(得分:1)

你在链中使用兄弟姐妹是选择另一个div,而不是你想要的那个。试试这个:

jQuery('#div1').show();
jQuery('#div2').hide();
jQuery('.showsearch').click(function () {
    jQuery('.searchbut').hide();
    jQuery('#div' + $(this).data('target')).show();
    jQuery(this).addClass('active').siblings().removeClass('active');
});

<强> jsFiddle example

我还建议使用自定义数据属性(data-),而不是在此处使用目标属性,除非您还需要使用目标属性。

答案 1 :(得分:1)

jQuery(function(){
    jQuery('#div1').show();
    jQuery('#div2').hide();
    jQuery('.showsearch').click(function(){
        jQuery('.searchbut').hide();
        jQuery('.showsearch.active').not(this).removeClass('active');
        jQuery(this).not('.active').addClass('active');
        jQuery( '#div'+$(this).data('target') ).show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<a id="buttonshowone" class="showsearch active" data-target="1">Properties For Sale</a>
<a id="buttonshowtwo" class="showsearch" data-target="2">Properties To Let</a>
</div>
<div id="div1" class="searchbut">div 1
</div>
<div id="div2" class="searchbut">div 2
</div>