【问题标题】:How should I close tooltip after user submits query with Bootstrap3-Typeahead?用户使用 Bootstrap3-Typeahead 提交查询后,我应该如何关闭工具提示?
【发布时间】:2016-07-08 00:05:53
【问题描述】:

我想通过将bootstrap3-typeahead.js(这是typeahead.js 的维护分支)与远程数据一起使用来提供预输入功能。但是,当用户快速键入并按 Enter 提交查询时,工具提示仍然显示。我认为解决此问题的一种简单方法是在用户按下回车键时简单地取消 ajax 请求。但是,这不起作用。

根据 charlietfl 的反馈,这是因为在用户按下任何键之前收到了请求。因此,当用户按下回车键时,也许我需要另一种方法来删除工具提示。我很乐意收到有关如何实现这一点的建议。

这是demo。例如,如果您快速键入“Dog”并按 Enter,我应该会中止请求,但结果仍在显示。

$(document).ready(function() {
    var req;
    $('.typeahead').typeahead(
      {
        name: 'animals',
        display: 'value',
        items: 'all',
        delay: 500,
        source: function(query, process) {
                var url = "http://api.gbif.org/v1/species/match?verbose=true&kingdom=Plantae&name=" + query;
                req = $.get(url, function(data) {
                    data =  $.map(data['alternatives'], function(name) {
                        return {
                            name: name['scientificName']
                        };
                    })
                    process(data);
                });

                return req
            }
      })
      .on('keydown', function(event) {
        console.log('keydown');
        if(event.which == 13) {
          console.log('enter key');
          if (req) {
            console.log('req',req);
            req.abort();
          }
        }
      });
});

问候

【问题讨论】:

  • 因为插件中还有另一个类似的事件处理程序。它支持键盘选择。您正在做的事情的逻辑不适合插件用户输入处理的流程
  • 你能详细说明你的答案吗?您的意思是 bootstrap3-typeahead 已经可以选择在某个按键按下后取消请求吗?
  • 不,我的意思是在任何人点击进入之前提出请求
  • 我明白了。用户提交查询后如何不显示建议?
  • 不知道。不知道你为什么需要

标签: javascript jquery xmlhttprequest typeahead.js bootstrap-typeahead


【解决方案1】:

暂时,我不得不切换到 typeahead.js 并使用它的typeahead('val', '') 功能在用户提交表单后立即清除输入字段。这样,建议不再显示。

但是,这不是一个理想的情况,因为正如我所说,typeahead.js 似乎不再维护。

为了将来参考,我开始使用 bootstrap3-typeahead 的原因是因为它在不包括其建议引擎 Bloodhound 的情况下更容易设置。不幸的是,Bloodhound 提供了节流和去抖动方法,这对于从远程源获取数据非常有用。目前,我正在通过这个绝妙的技巧提供类似的功能(来源:http://codetunnel.io/how-to-implement-autosave-in-your-web-app/):

var timeOutId;

$('.typeahead').typeahead({ // your options
}, {
name: 'someName', 
display: 'value',
source: (query, syncResults, asyncResults) => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
            $.get(my_backend + query, function(data) {
                data =  $.map(data.suggestions, function(suggestion) {
                    return {
                        value: suggestion
                    };
                })
                asyncResults(data);
            });
        }, 750);
}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多