开发者

jQuery - Show box/Hide on event doesn't work. why?

I am using this function to show a list (ul) on click and hide it if someone click elsewhere on the page. It doesn't seem to work:

$(document).ready(function() {
    $('#trigger').click(function() {
        $('#dropdown-options').show();
    });

    $(document).click(function() {
        $('#dropdown-options').hide();
    });

    $('#dropdown-options').click(function(e) 开发者_Python百科{
        e.stopPropagation();
    });
});

(I am using Ruby on Rails, and it seems everything should be under $(document).ready(function() {...}); in order to make it work.)


It's actually because document contains "#trigger", it is being shown and hidden at the same time. Move the "stopPropagation" up into the "#trigger" selector, you need to stop the prop of the event before the document gets it and hides again.

$(document).ready(function() {
  $('#trigger').click(function(e) {
    e.stopPropagation();
    $('#dropdown-options').show();
  });

  $(document).click(function() {
    $('#dropdown-options').hide();
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜