开发者

jQuery - How to hide drop down search result list?

I'm trying to do a search user bar like the one in facebook (it consists in a input area and a dynamic drop down result list)

but I'm having problems in hiding the drop down result list list when I click in another area.

the html code is something like this:

<div id="search_container">
  <input id="search_imput" type="text" autocomplete="off">
  <ul id="search_result_list">
    <li>result 1</li>
    <li>result 2</li>
    <li>result 3</li>
  </ul>
</div>

and the jquery code near this:

$('#search_imput').click(function(){
  //update_search_result_list();
  $('#search_result_list').show();      
});

$('#search_container').focusout(function(){
  $('#search_result_list').hide();
});

$('#search_result_list').children('li').开发者_运维问答click(function(){
  //display_selected_user_info();
  alert(($(this).text());
});

but it doesn't trigger the display_selected_user_info();

The main problem is that the #search_container focusout is triggered before the $('#search_result_list').children('li') click is activated, making the li item disappear before the click li function is activated.


Note: I've placed a example were u can test here.


I finally find out how to do. (after a lot of search)

Basically i can use the document click event and the event.trigger to check if i click or not in my result list.

// remove the $('#search_container').focusout and use this one:
$(document).unbind('click');
$(document).click(function(event){
  if($(event.target).closest('#search_container').length == 0) {
    $('#search_result_list').hide();
  }
});

I've put the complete version of my example here


I've found a simple work around to this problem. You can introduce a delay before the result list hides, so that the click event will have enough time to fire.

$('#search_imput').blur(function() {
    setTimeout(function(){
        $('#search_result_list').hide();
    }, 100);
});

See the updated version: http://jsfiddle.net/5FRar/1/


is ur list generated dynamically? if yes den try live function to detect new li added to dom and the jquery for dis is:

$('#search_result_list li').live('click', function(){
  display_selected_user_info();
});


EDITED

$('#search_imput').click(function(){
  //update_search_result_list();
  $(this).find('#search_result_list').children('li').show();       
});

$('#search_container').unbind().bind('blur',function(){
  $(this).find('#search_result_list').children('li').hide();
});

$('#search_result_list').children('li').die().live('click',function(){
  display_selected_user_info();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜