I have a small problem identifying an item with jQuery. Let me explain better :)
I have a menu that appears when the user clicks on a button. This is working perfectly. Then, I want this menu to go away when the user clicks on any part of the site except on the menu. This is also working great, but with a small problem: in the menu, there is an item that allows the user to choose from an autocomplete list. This list was done using jquery-ui autocomplete. When the user clicks on an item here, the menu disappears (it shouldn't :) ), and I don't know how to make the exception for this, since I don't know how can I grab the item, can I grab it by class? Does it have an id?
I have the following code to identify where the click is being done and proceed (you can see that if menu-button or menu are clicked the menu will not hide). How do I make the exception when the click is made in autocomplete of jQuery-ui?
$(document).click(function(event) {
if($(event.target).parents().index($('#menu')) 开发者_如何学编程== -1 && $(event.target).parents().index($('#menu-button')) == -1) {
if($('#menu').is(":visible")) {
$('#menu').hide(500);
}
}
});
Thanks!
The autocomplete ul
has a class of ui-autocomplete
. So you can get it by doing $(".ui-autocomplete")
.
However, my preferred method for doing what you are trying to do would be to do this:
$(".ui-autocomplete").click(function(e){
e.stopPropagation();
//... and maybe some other stuff
}
This basically will stop the click from bubbling up, so it will not trigger the document click.
You can pick up those items by their class. I think I would change it to be:
$(document).click(function(event) {
if($(event.target).parents().index($('#menu')) == -1 &&
$(event.target).parents().index($('#menu-button')) == -1 &&
$(event.target).parents().index($('.ui-autocomplete-input')) == -1 &&
$(event.target).parents().index($('.ui-autocomplete')) == -1 ) {
if($('#menu').is(":visible")) {
$('#menu').hide(500);
}
}
});
精彩评论