简体   繁体   English

为什么此脚本仅适用于双击而不是单击?

[英]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. 上面的脚本可以工作,但是要使其执行fadeIn,需要单击两次。 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. 一旦发生该事件,您就可以查看具体单击的内容(evt.target),然后从那里有条件地触发功能。

http://codepen.io/snypelife/pen/Fcjiw 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. click事件(与其他大多数事件一样)冒泡到父元素。 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'. 这实际上意味着,当您单击'.click1'元素时,此事件首先在此元素上触发,然后在'body'上触发。 And the event listener on 'body' instantly hides the element. 而且“ body”上的事件侦听器会立即隐藏该元素。 You can use Event.stopPropagation() here to prevent event bubbling: 您可以在此处使用Event.stopPropagation()防止事件冒泡:

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

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

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

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