Javascript/jQuery将输入值与数组进行比较 [英] Javascript/jQuery compare input value to array
问题描述
我对javascript和jquery比较陌生.现在,我在txt文件中有一个单词列表.我将此列表存储在一个数组中,我想将该数组的内容与某些用户输入进行比较.如果匹配,则应显示该特定单词.
I'm relatively new to javascript and jquery. Right now I have a list of words in a txt file. I store this list in an array, and I want to compare the contents of that array to some user input. If there's a match, that specific word should be displayed.
我还使用 Jasny Bootstrap 来执行一些预输入功能来预测哪些单词用户想要搜索.
I also use Jasny Bootstrap to perform some typeahead functions to predict which words the user would like to search for.
在当前阶段,我的函数在第一个输入字符上找到匹配项.当使用更多字符时,该函数返回未找到匹配项.为什么会这样?
In the current stage, my function finds matches on the first input character. When using more characters the function returns that no match has been found. Why is that?
这是我的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..");
}
};
推荐答案
您没有使用jquery,而只是使用本地javascript.
You didn't use jquery, just native javascript.
读取脚本文件后,只需执行以下操作:
After your script reading file, just do:
$(searchinput).on("keypress", function() {
if ($.inArray(formInput,myArray) > -1) {
alert("There's a match!");
}
});
更新
$(searchinput).on("blur", function() {
if ($.inArray(formInput,myArray) > -1) {
alert("There's a match!");
}
});
这篇关于Javascript/jQuery将输入值与数组进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!