簡體   English   中英

Javascript / jQuery將輸入值與數組進行比較

[英]Javascript/jQuery compare input value to array

我對javascript和jquery比較陌生。 現在我有一個txt文件中的單詞列表。 我將此列表存儲在一個數組中,我想將該數組的內容與某些用戶輸入進行比較。 如果匹配,則應顯示該特定單詞。

我還使用Jasny Bootstrap執行一些預輸入功能來預測用戶想要搜索的單詞。

在當前階段,我的函數在第一個輸入字符上找到匹配項。 當使用更多字符時,該函數返回未找到匹配項。 這是為什么?

這是我的HTML:

<div class="container">

  <div class="appwrapper">
    <div class="content">
        <h3>OpenTaal Woordenboek</h3>
        <p>Voer uw zoekopdracht in:<p>
        <p><input name="searchinput" id="searchinput" data-provide="typeahead" type="text" placeholder="Zoeken...">
    <p class="dict"></p>
    </div>
  </div>

</div> <!-- /container -->

這是jQuery:

<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap-typeahead.js"></script>

<script type="text/javascript">
var data;
var myArray = [];
var txtFile = new XMLHttpRequest();
        txtFile.open("GET", "OpenTaal-210G-basis-gekeurd.txt", true);
        txtFile.onreadystatechange = function() {
    if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
            if (txtFile.status === 200) {  // Makes sure it's found the file.
            allText = txtFile.responseText;
            data = txtFile.responseText.split("\n"); // Will separate each line into an array
            myArray = [data];
        } //"\r\n" 
    }
}
//console.write(data);

searchinput.onkeypress = function() {
//alert("The function is working!");
var formInput = document.getElementById("searchinput").value;

   if (myArray == formInput) {
   alert("There's a match!");
   $('.dict').append('<div class="result">' + myArray + '</div>')
   } else {
      alert("No match has been found..");
   }
 };

您需要搜索整個數組,而不僅僅是將其與值進行比較:

if ($.inArray(formInput,myArray)>=0) { // returns -1 if no match
   alert("There's a match!");

http://api.jquery.com/jQuery.inArray/

您沒有使用jquery,僅使用了本地javascript。

腳本讀取文件后,只需執行以下操作:

$(searchinput).on("keypress", function() {
   if ($.inArray(formInput,myArray) > -1) {
      alert("There's a match!");
   }
});

UPDATE

$(searchinput).on("blur", function() {
   if ($.inArray(formInput,myArray) > -1) {
      alert("There's a match!");
   }
});

遍歷數組並將輸入值與數組元素匹配,例如:

   for(var i in myArray) {
       var arrayElement = myArray[i];
       if (arrayElement == formInput) {
            //Do your stuff
       }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM