避免使用JQuery同时显示2个项目

时间:2016-08-21 14:16:17

标签: jquery animation

在用户点击其正确按钮后显示2个隐藏框(“return_policy”和“risk_free”),如何避免同时显示2个框?

<style>
 .info_dropdown { display: none; }
</style>

<button class="return_policy">30 DAY MONEY BACK GUARANTEE</button>
<button class="risk_free">100% RISK FREE PURCHASE</button>

<div class="info_dropdown" id="return_policy">
 <p>Lorem Ipsum</p>
 <p class="close_info">Close</p>
</div>

<div class="info_dropdown" id="risk_free">
 <p>Lorem Ipsum</p>
 <p class="close_info">Close</p>
</div>

<script>
$('.return_policy').click(function(){
    $('#return_policy').slideToggle();
});

$('.risk_free').click(function(){
    $('#risk_free').slideToggle();
});

//Close the proper info box
$('.close_info').click(function(){
    $(this).parent().slideToggle();
});
</script>

2 个答案:

答案 0 :(得分:1)

更新jsfiddle。你的jquery代码有一些错误。 return_policyrisk_free id而非class因此您应使用#通过jquery获取这些元素

$('.return_policy').click(function(){
    $('#return_policy').slideToggle();
    $('#risk_free').css('display','none');
});

$('.risk_free').click(function(){
    $('#risk_free').slideToggle();
    $('#return_policy').css('display','none');
});

答案 1 :(得分:1)

像这样的东西

$(function() {
  $('.btn').on("click", function(e) {
    e.preventDefault(); // in case you forget type="button"
    var $thisDiv = $("#" + $(this).data("id")); // get attribute from button
    $thisDiv.slideToggle(); // toggle the div
    $(".info_dropdown").not($thisDiv).toggle(false); // hide the other
  });

  //Close the proper info box
  $('.close_info').click(function() {
    $(this).parent().slideToggle();
  });
});
.info_dropdown {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="btn" data-id="return_policy">30 DAY MONEY BACK GUARANTEE</button>
<button type="button" class="btn" data-id="risk_free">100% RISK FREE PURCHASE</button>

<div class="info_dropdown" id="return_policy">
  <p>Lorem Ipsum 1</p>
  <p class="close_info">Close</p>
</div>

<div class="info_dropdown" id="risk_free">
  <p>Lorem Ipsum 2</p>
  <p class="close_info">Close</p>
</div>