javascript - 我无法用我的函数隐藏 jquery 自动完成功能

标签 javascript jquery jquery-ui autocomplete

我正在创建一个项目,它使用 JSON 动态搜索音乐。
这是我的html:

    <div id="custom-search-input">
        <div class="input-group col-md-12">
            <input type="text" class="form-control input-lg" placeholder="Search query..." id="searchquery" autocomplete="off" />
            <span class="input-group-btn">
                <button class="btn btn-info btn-lg" type="button" id="searchbuttonheader" onclick="search();">
                    <i class="glyphicon glyphicon-search"></i>
                </button>
            </span>
        </div>
    </div>

我的搜索函数称为search(); ...在集成jquery自动完成之前,当我在searchquery输入中单击键盘上的ENTER时,它会执行搜索(); 函数。为此,我的 JS 代码如下:

    // ENTER KEY SEARCH //
$.fn.enterKey = function (fnc) {return this.each(function () {$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {search();}})})
}
$("#searchquery").enterKey(function () {search();});
    // ENTER KEY SEARCH //

好吧,它正在工作......但是......

集成后,当我在 searchquery 输入中输入内容时,jquery 自动完成会提供一些自动完成数据。这是JS:

$('#searchquery').autoComplete({
    minChars: 1,
    delay: 500,
    source: function(term, response){
        $.getJSON('<?php echo $url_autocomplete; ?>', { query: term }, function(data){ response(data); });
    },
    onSelect: function(e, term, item){
        search();
        //alert('Item selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.');
    }
});

当我单击其中一个时,自动完成功能会隐藏并搜索文本。但是,当我不选择其中任何一个并按 Enter 键时,它会进行搜索,但自动完成功能不会隐藏。

我想要: 当我在 searchquery 输入中输入内容时,我按 Enter 键隐藏自动完成建议并进行 search();

最佳答案

您没有使用 jquery-ui-autocomplete 但使用 jQuery-autoComplete来自Pixabay我对吗?好吧,看了代码,没有提供close方法,所以我在原来的源码中添加了一个。您可以复制并使用下面的 jquery.auto-complete.js 并调用 $("#searchquery").autoComplete('close'); 来关闭建议。请参阅下面的示例如何使用它:

$("#searchquery").enterKey(function (e) {
    $("#searchquery").autoComplete('close');
    // .. DO YOUR SEARCH HERE ..
});

使用下面修改后的 jquery.auto-complete.js。

/*
	jQuery autoComplete v1.0.7
    Copyright (c) 2014 Simon Steinberger / Pixabay
    GitHub: https://github.com/Pixabay/jQuery-autoComplete
	License: http://www.opensource.org/licenses/mit-license.php
*/

(function($){
    $.fn.autoComplete = function(options){
        var o = $.extend({}, $.fn.autoComplete.defaults, options);

        // public methods
        if (typeof options == 'string') {
            this.each(function(){
                var that = $(this);
                if (options == 'destroy') {
                    $(window).off('resize.autocomplete', that.updateSC);
                    that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
                    if (that.data('autocomplete'))
                        that.attr('autocomplete', that.data('autocomplete'));
                    else
                        that.removeAttr('autocomplete');
                    $(that.data('sc')).remove();
                    that.removeData('sc').removeData('autocomplete');
                } else if (options == 'close') { 
                    // Add new method to close the suggestion box
                    $(that.data('sc')).hide();
                 }
            });
            return this;
        }

        return this.each(function(){
            var that = $(this);
            // sc = 'suggestions container'
            that.sc = $('<div class="autocomplete-suggestions '+o.menuClass+'"></div>');
            that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
            that.attr('autocomplete', 'off');
            that.cache = {};
            that.last_val = '';

            that.updateSC = function(resize, next){
                that.sc.css({
                    top: that.offset().top + that.outerHeight(),
                    left: that.offset().left,
                    width: that.outerWidth()
                });
                if (!resize) {
                    that.sc.show();
                    if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
                    if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
                    if (that.sc.suggestionHeight)
                        if (!next) that.sc.scrollTop(0);
                        else {
                            var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
                            if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
                                that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
                            else if (selTop < 0)
                                that.sc.scrollTop(selTop + scrTop);
                        }
                }
            }
            $(window).on('resize.autocomplete', that.updateSC);

            that.sc.appendTo('body');

            that.sc.on('mouseleave', '.autocomplete-suggestion', function (){
                $('.autocomplete-suggestion.selected').removeClass('selected');
            });

            that.sc.on('mouseenter', '.autocomplete-suggestion', function (){
                $('.autocomplete-suggestion.selected').removeClass('selected');
                $(this).addClass('selected');
            });

            that.sc.on('mousedown', '.autocomplete-suggestion', function (e){
                var item = $(this), v = item.data('val');
                if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
                    that.val(v);
                    o.onSelect(e, v, item);
                    that.sc.hide();
                }
                return false;
            });

            that.on('blur.autocomplete', function(){
                try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover
                if (!over_sb) {
                    that.last_val = that.val();
                    that.sc.hide();
                    setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input
                } else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20);
            });

            if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); });

            function suggest(data){
                var val = that.val();
                that.cache[val] = data;
                if (data.length && val.length >= o.minChars) {
                    var s = '';
                    for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
                    that.sc.html(s);
                    that.updateSC(0);
                }
                else
                    that.sc.hide();
            }

            that.on('keydown.autocomplete', function(e){
                // down (40), up (38)
                if ((e.which == 40 || e.which == 38) && that.sc.html()) {
                    var next, sel = $('.autocomplete-suggestion.selected', that.sc);
                    if (!sel.length) {
                        next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
                        that.val(next.addClass('selected').data('val'));
                    } else {
                        next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
                        if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
                        else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
                    }
                    that.updateSC(0, next);
                    return false;
                }
                // esc
                else if (e.which == 27) that.val(that.last_val).sc.hide();
                // enter or tab
                else if (e.which == 13 || e.which == 9) {
                    var sel = $('.autocomplete-suggestion.selected', that.sc);
                    if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function(){ that.sc.hide(); }, 20); }
                }
            });

            that.on('keyup.autocomplete', function(e){
                if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
                    var val = that.val();
                    if (val.length >= o.minChars) {
                        if (val != that.last_val) {
                            that.last_val = val;
                            clearTimeout(that.timer);
                            if (o.cache) {
                                if (val in that.cache) { suggest(that.cache[val]); return; }
                                // no requests if previous suggestions were empty
                                for (var i=1; i<val.length-o.minChars; i++) {
                                    var part = val.slice(0, val.length-i);
                                    if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
                                }
                            }
                            that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
                        }
                    } else {
                        that.last_val = val;
                        that.sc.hide();
                    }
                }
            });
        });
    }

    $.fn.autoComplete.defaults = {
        source: 0,
        minChars: 3,
        delay: 150,
        cache: 1,
        menuClass: '',
        renderItem: function (item, search){
            // escape special characters
            search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
            var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
            return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
        },
        onSelect: function(e, term, item){}
    };
}(jQuery));

关于javascript - 我无法用我的函数隐藏 jquery 自动完成功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33905849/

相关文章:

javascript - IE 的 CSS3 Box 半径模拟的哪种解决方案渲染速度最快?

javascript - D3 中 jQuery 的 $ (".cell:first") 是什么?

javascript - jQuery 验证插件无法识别有效输入

javascript - Jquery UI drop event plain/text between text in Div contentEditable

jQuery - 使用 SlideToggle 功能渲染多个 div 元素

javascript - 如何并行上传多个文件到亚马逊S3?

javascript - 遍历数组中的项目以分配数据 ID,但仅获取数组中的最后一项

javascript - 带有来自类别列表的字典数组的 JS Autobuild 表

optimization - 如何在对 PHP 的 ajax 调用返回之前获取加载事件

javascript - jquery datepicker 无法在 <h :form> 内工作