0

我想通過使用bootstrap3-typeahead.js(這是維護的分叉typeahead.js)與遠程數據提供打字頭功能。但是,當用戶快速鍵入並按Enter鍵提交查詢時,工具提示仍然顯示。我認爲解決這個問題的一個簡單方法就是在用戶按下回車鍵時簡單地取消ajax請求。但是,這不起作用。用戶使用Bootstrap3-Typeahead提交查詢後應如何關閉工具提示?

根據charlietfl的反饋,這是因爲在用戶按任何鍵之前接收到請求。因此,當用戶按下回車鍵時,可能需要另一種方法來刪除工具提示。我很樂意收到有關如何實現這一目標的建議。

這是demo。例如,如果快速輸入「Dog」並按回車鍵,我應該中止請求,但結果仍顯示出來。

$(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(); 
      } 
     } 
     }); 
}); 

問候

+0

因爲在插件的另一個類似的事件處理程序。它支持鍵盤選擇。你正在做什麼的邏輯不適合插件用戶輸入處理的流程 – charlietfl

+0

你能詳細說明你的答案嗎?你的意思是說,bootstrap3-typeahead在某些按鍵之後已經有了一個取消請求的選項? –

+0

不,我的意思是,請求是在任何人點擊前輸入 – charlietfl

回答

0

暫時,我只好改用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); 
}})