jQuery show hide多个Div无法正常工作

时间:2016-06-02 14:45:05

标签: javascript jquery html css

我在页面中显示/隐藏多个div的jQuery代码:

$(function() {
    $('#toggle').click(function(event) {
        event.preventDefault();
        var target = $(this).attr('href');
        $(target).toggleClass('hidden show');
    });
});
<span class="add-btn">
    <a href="#options" id="toggle">
        <span class="btn btn-primary btn-sm">
            <i class="fa fa-filter"></i>
            Filter
        </span>
    </a>
</span>
<div id="options" class="well hidden">hehe</div>    
<span class="add-btn">
    <a href="#options2" id="toggle">
        <span class="btn btn-primary btn-sm">
            <i class="fa fa-filter"></i>
            Filter2
        </span>
    </a>
</span>
<div id="options2" class="well hidden">hoho</div>
.show {
    display: block !important;
}
.hidden {
    display: none !important;
    visibility: hidden !important;
}

但在行动中不行!怎么解决这个问题?!

Demo

2 个答案:

答案 0 :(得分:1)

您需要将id个触发器设为唯一标识符,它们可以相同。代码将仅评估第一个实例并忽略任何其他实例。

$(function() {

       $('#toggle1, #toggle2').click(function(event) {
         event.preventDefault();
         var target = $(this).attr('href');
         $(target).toggleClass('hidden show');
       });
});

示例:

&#13;
&#13;
 $(function() {

       $('#toggle1, #toggle2').click(function(event) {
         event.preventDefault();
         var target = $(this).attr('href');
         $(target).toggleClass('hidden show');
       });
});
&#13;
.show {
    display: block !important;
}
.hidden {
    display: none !important;
    visibility: hidden !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="add-btn"><a href="#options" id="toggle1">
              <span class="btn btn-primary btn-sm"><i class="fa fa-filter"></i>Filter</span></a>
</span>



<div id="options" class="well hidden">hehe</div>

<span class="add-btn"><a href="#options2" id="toggle2">
              <span class="btn btn-primary btn-sm"><i class="fa fa-filter"></i>Filter2</span></a>
</span>



<div id="options2" class="well hidden">hoho</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您不能分配相同的ID,而是使用类:

HTML

<span class="add-btn"><a href="#options" class="toggle">
          <span class="btn btn-primary btn-sm"><i class="fa fa-filter">     </i>Filter</span></a>
 </span>

<div id="options" class="well hidden">hehe</div>

<span class="add-btn"><a href="#options2" class="toggle">
          <span class="btn btn-primary btn-sm"><i class="fa fa-filter">     </i>Filter2</span></a>
</span>

<div id="options2" class="well hidden">hoho</div>

JS

 $(function() {

   $('.toggle').click(function(event) {
     event.preventDefault();
     var target = $(this).attr('href');
     $(target).toggleClass('hidden show');
   });
})

CSS

.show {
    display: block !important;
}
.hidden {
    display: none !important;
    visibility: hidden !important;
}