简体   繁体   English

单击隐藏/显示div

[英]Hiding/Showing divs on click

I have created a script that when a button is clicked it displays all of the content beneath it and hides the other buttons content. 我创建了一个脚本,当单击一个按钮时,它会显示其下面的所有内容并隐藏其他按钮内容。 The only problem I'm having is that I want to refactor the script so it only works if you hit the button , instead of the entire div the button sits in as it's causing some confusion. 我遇到的唯一问题是我想要重构脚本, 这样只有按下按钮才能工作 ,而不是按钮所在的整个div,因为它会造成一些混乱。 What would be the best way about this? 对此最好的方法是什么?

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

jQuery: jQuery的:

(function($) {

  $(".signup-button").on('click', function() {
    $(".signup-button").not(this).find(".signup-form").hide();
    $(this).find(".signup-form").toggle("slow");
  });

})(jQuery);

JSFiddle: https://jsfiddle.net/v6bmphct/3/ JSFiddle: https ://jsfiddle.net/v6bmphct/3/

One option would be to attach the event listener directly to the descendant button element. 一种选择是将事件监听器直接附加到后代按钮元素。 In doing so, the click event isn't triggered when clicking on the other content. 这样, click其他内容时不会触发click事件。 You would also have to change instances of $(this) to $(this).parent() or $(this).closest('.signup-button') . 您还必须将$(this)实例更改为$(this).parent()$(this).closest('.signup-button')

Updated Example 更新的示例

$(".signup-button .btn").on('click', function(e) {
  $(this).parent().find(".signup-form").toggle("slow");
  $(".signup-button").not($(this).parent()).find(".signup-form").hide();
});

Alternatively, since event.target is a reference to the clicked element, you could also just check to see if event.target is the button element by using the .is() method: 或者,由于event.target是对单击元素的引用,您还可以使用.is()方法检查event.target是否为按钮元素:

Updated Example 更新的示例

$(".signup-button").on('click', function(e) {
  if ($(e.target).is('.btn')) {
    $(this).find(".signup-form").toggle("slow");
    $(".signup-button").not(this).find(".signup-form").hide();
  }
});

Check this out: 看一下这个:

(function($) {

  $(".signup-button").find('button').on('click', function() {
    $(this).siblings(".signup-form").toggle("slow");
    $(".signup-button").not(this.closest(".signup-button")).find(".signup-form").hide();
  });

})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM