JQuery UI 自动完成 - 点击回车后隐藏列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9602395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:02:47  来源:igfitidea点击:

JQuery UI autocomplete - Hide list after hiting enter

jqueryjquery-ui-autocomplete

提问by Marc

I have an input. I use the Jquery UI autocomplete to propose suggestions to the user. Lets image I have in my list 3 items: item1, item2, item3. What I am looking for is the list to be closed when the user hits enter. For instance if the user only enters "it", all 3 elements will be displayed. In that case if he hits enter I would like the list to be closed. I do not manage to comue up with a solution for that. Hope someone can help. Cheers. Marc.

我有一个输入。我使用 Jquery UI 自动完成向用户提出建议。让我的列表中有 3 个项目的图像:item1、item2、item3。我正在寻找的是当用户点击进入时要关闭的列表。例如,如果用户只输入“it”,则将显示所有 3 个元素。在这种情况下,如果他按回车键,我希望关闭列表。我没有设法想出一个解决方案。希望有人能帮忙。干杯。马克。

http://jsfiddle.net/vXMDR/

http://jsfiddle.net/vXMDR/

My html:

我的html:

<input id="search" type="input" />?

My js:

我的js:

$(function() {

    var availableTags = [
            "item1","item2","item3"
        ];

    $("#search").autocomplete({
        source:availableTags,
        minLength: 0
        });
});?

回答by shanabus

Here is the solution: http://jsfiddle.net/vXMDR/3/

这是解决方案:http: //jsfiddle.net/vXMDR/3/

Let me know if you have questions.

如果您有任何疑问,请告诉我。

The magic is binding the autocomplete close method to keypress

神奇的是将自动完成关闭方法绑定到按键

 $("#search").keypress(function(e){ 
    if (!e) e = window.event;   
    if (e.keyCode == '13'){
      $('#search').autocomplete('close');
      return false;
    }
  });

UPDATE

更新

$("#search").keypress(function(e){binds keypress of the #search element to the function specified, passing in the eventobject. You could also write this as $("#search").on('keypress', function(e) {...

$("#search").keypress(function(e){将#search 元素的按键绑定到指定的函数,传入event对象。你也可以这样写$("#search").on('keypress', function(e) {...

if (!e) e = window.event;ensures that if a valid event was not passed in, it sets eto the current window.event object.

if (!e) e = window.event;确保如果未传入有效事件,则将其设置e为当前 window.event 对象。

Finally, if (e.keyCode == '13'){tests that event keycode value is equal to the 'enter' key. For a list of valid keycodes, see here.

最后,if (e.keyCode == '13'){测试事件键码值是否等于“输入”键。有关有效键码的列表,请参见此处

Here is the documentation for autocomplete close method - http://docs.jquery.com/UI/Autocomplete#method-close

这是自动完成关闭方法的文档 - http://docs.jquery.com/UI/Autocomplete#method-close

回答by karim79

$(function() {

    var availableTags = [
            "item1","item2","item3"
        ];

    $("#search").autocomplete({
        source:availableTags,
        minLength: 0
    }).keyup(function (e) {
        if(e.which === 13) {
            $(".ui-menu-item").hide();
        }            
    });
});?

http://jsfiddle.net/vXMDR/2/

http://jsfiddle.net/vXMDR/2/

回答by Martin Capodici

I have modified the shanabus solution further, to allow for the time delay due to the callback.

我进一步修改了 shanabus 解决方案,以考虑由于回调而导致的时间延迟。

http://jsfiddle.net/vXMDR/46/

http://jsfiddle.net/vXMDR/46/

This is a simple hack to store whether or not to display the autocomplete as a boolean. (I am using setTimeOut to create the scenario where there is a wait, it is the problem scenario not the solution.)

这是一个简单的技巧,用于存储是否将自动完成显示为布尔值。(我正在使用 setTimeOut 创建等待的场景,这是问题场景而不是解决方案。)

shouldComplete = true;

$("#search").autocomplete({
    source:function (request, response) {            
        setTimeout(
            function() {
                response(shouldComplete ? availableTags : null);
            },
            2000);
    }        
    ,
    minLength: 0
    });

Then when the enter button is pressed the flag is set to false. Any other key reactivates the flag.

然后当按下回车按钮时,标志设置为假。任何其他键都会重新激活该标志。

$("#search").keypress(function(e){
    if (!e) e = window.event;   
    if (e.keyCode == '13'){
      $('#search').autocomplete('close');
        shouldComplete = false;
      return false;
    }
        else
        {
            shouldComplete = true;
        }
  });

It is possible to do this more elegantly I am sure, but this does solve the problem that the drop down might appear later on.

我确信可以更优雅地执行此操作,但这确实解决了稍后可能会出现下拉列表的问题。

回答by Sean

I ran into this issue and was not able to use the close() method because my autocomplete was being re-rendered on every load of a Backbone view. As such, a new autocomplete element was appended to the DOM and those stuck around even though the attached input element was getting blown away and recreated. The superfluous autocomplete elements were causing a few problems, but the worst was when the user pressed enter quickly enough, I would go through this sequence:

我遇到了这个问题并且无法使用 close() 方法,因为每次加载 Backbone 视图时都会重新渲染我的自动完成功能。因此,一个新的自动完成元素被附加到 DOM 中,即使附加的输入元素被吹走并重新创建,这些元素也会被卡住。多余的自动完成元素导致了一些问题,但最糟糕的是当用户按下 Enter 的速度足够快时,我会按照以下顺序进行:

  1. User types text
  2. Request for suggestions begins execution
  3. The keypress event is triggered and executes a full text search (the user did not select something from autocomplete)
  4. The view reloads, the input field and other elements are re-rendered and a new autocomplete element is appended to the end of the DOM
  5. The original request for suggestions returns with a response and the suggestions are displayed.
  1. 用户输入文本
  2. 征求建议开始执行
  3. keypress 事件被触发并执行全文搜索(用户没有从自动完成中选择某些内容)
  4. 视图重新加载,输入字段和其他元素被重新渲染,一个新的自动完成元素被附加到 DOM 的末尾
  5. 原始的建议请求返回响应并显示建议。

Note that the suggestions displayed in step 5 are now tied to an autocomplete container that is no longer associated with my input field, so any events like pressing esc or clicking elsewhere on the screen will do nothing. The suggestions are stuck there until a full reload of the page occurs.

请注意,第 5 步中显示的建议现在与不再与我的输入字段相关联的自动完成容器相关联,因此任何事件(如按 esc 或单击屏幕上的其他位置)都将不起作用。这些建议会一直停留在那里,直到完全重新加载页面。

I ended up fixing this by storing the mainContainerId of the most recently created autocomplete element and removing it manually.

我最终通过存储最近创建的自动完成元素的 mainContainerId 并手动删除它来解决这个问题。

// during rendering
self.currentAutoComplete = $("#input-element").autocomplete({
  // set options
});

// later
if (this.currentAutoComplete) {
  $("#" + this.currentAutoComplete.mainContainerId).remove();
}