简体   繁体   中英

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. 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:

(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/

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. You would also have to change instances of $(this) to $(this).parent() or $(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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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