简体   繁体   中英

Why is this script only work on double click rather than single click?

Code:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function () {

$('.click1').click(function () {
    $(".show1").fadeIn(400);
});

$('body, .click1').click(function() { 
    $('.show1').hide(); 
});
});
</script>

The script above works but in order for it to do the fadeIn it needs to be clicked twice. How can I change it so that it shows when clicked once?

For your use case, you can apply the event listener to the body of the document (in this case, you're listening for when a click happens anywhere on the page). Once that event occurs, you can see what was clicked specifically (evt.target) and from there conditionally fire functions.

http://codepen.io/snypelife/pen/Fcjiw

$(function () {

      $('body').on('click', function (evt) {
        if($(evt.target).hasClass('click')){
          $('.show').toggle('fade');
        } else {
          $('.show').fadeOut();
        }
      });

});

The click event (as the most of the other events) bubbles to the parent elements. It effectively means that when you click on the '.click1' element this event first triggered on this element and then it is triggered on 'body'. And the event listener on 'body' instantly hides the element. You can use Event.stopPropagation() here to prevent event bubbling:

$('.click1').click(function (e) {
    $(".show1").fadeIn(400);
    e.stopPropagation();
});

$('body').click(function() { 
    $('.show1').hide(); 
});

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