如何使下拉列表自动完成以消失onblur或在jQuery中单击外部? [英] how to make the dropdown autocomplete to disappear onblur or click outside in jquery?

查看:77
本文介绍了如何使下拉列表自动完成以消失onblur或在jQuery中单击外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是调用该功能以在搜索框中显示自动完成功能...我希望自动完成功能在onBlur上消失或在搜索框外单击...请告诉我该功能中应添加什么以使在外部单击时,自动完成下拉菜单会消失吗?

Below is the function which is called to show the autocomplete in a search box...I want the auto complete to disappear onBlur or click outside the search box...please tell me what should be added in this function to make the autocomplete drop down disappear when clicked outside?

function hideLoader(){
        $('#sub_cont').fadeIn(100);
        $('.search-background').fadeOut(100);
    };

    $('#search').keyup(function(e) {
      if(e.keyCode == 13) {
        showLoader();
        $('#sub_cont').fadeIn(100);
        $("#content #sub_cont").load("../ajax/search.php?val=" + $("#search").val(), hideLoader());
        }
      });

//Fading out the div when the text box is empty
    String.prototype.trim = function() {
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        }

    $(".searcher").keyup(function(){

        if($('.searcher').val().trim().length > 0) {
            // is not empty
            showLoader();
            $('#sub_cont').fadeIn(100);
            $("#content #sub_cont").load("../ajax/search.php?val=" + $("#search").val(), hideLoader());
        } else {
            // is empty
            $('#sub_cont').fadeOut(100);
        }

    });

推荐答案

您可以尝试将click事件绑定到文档.像这样:

You could try binding the click event to the document. Something like this:

$(document).bind('click', function (event) {
    // Check if we have not clicked on the search box
    if (!($(event.target).parents().andSelf().is('.searcher'))) {
        // Hide/collapse your search box, autocomplete or whatever you need to do
    }
});

这篇关于如何使下拉列表自动完成以消失onblur或在jQuery中单击外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆