单击按钮时切换其他div

时间:2018-04-13 08:03:40

标签: javascript jquery html

如何在单击按钮时将其他div切换为关闭?

$(".slider-wrapper button").click(function() {
  $(this).parent().find(".slider-content").slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>

<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>

3 个答案:

答案 0 :(得分:3)

这是你想要的吗?

$(".slider-wrapper button").click(function() {
  $(".slider-content:visible").add($(this).next()).slideToggle();
});

它将隐藏那些可见的并显示与您单击的按钮对应的那个。

<强>演示

$(".slider-wrapper button").click(function() {
  $(".slider-content:visible").add($(this).next()).slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>

<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>

答案 1 :(得分:0)

尝试使用javascript,

&#13;
&#13;
<div class="slider-wrapper">
    <button id="btn1" onClick="myFunction()" >btn 1</button>
    <div id="div1" style="display: block;" class="slider-content">Foo</div>
</div>

<div class="slider-wrapper">
    <button id="btn2" onClick="myFunction()" >btn 2</button>
    <div id="div2" style="display: block;"  class="slider-content">Foo</div>
</div>

<script type="text/javascript">

function myFunction() {


       var btn1= document.getElementById("btn1");
       var btn2= document.getElementById("btn2");

       var div1= document.getElementById("div1");
       var div2= document.getElementById("div2");

       btn1.onclick = function() {
         div1.style.display = "block";
         div2.style.display = "none";
       };

       btn2.onclick = function() {
         div1.style.display = "none";
         div2.style.display = "block";
       };


}

</script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以让它非常简单Jquery:

&#13;
&#13;
$(".slider-wrapper button").click(function() {
  $(this).parent().siblings(".slider-wrapper").children(".slider-content").slideToggle();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>

<div class="slider-wrapper">
  <button>OPEN ME</button>
  <div class="slider-content">Foo</div>
</div>
&#13;
&#13;
&#13;