我正在学习使用Javascript进行自动填充。
这是我正在使用的示例代码,它有效,我需要了解它的流程。
当您在输入标签中输入JO时,会显示“john doe”选项
// variables
var input = document.querySelector('#autocomplete-input');
var people = ['john doe', 'maria', 'paul', 'george', 'jimmy'];
var results;
// functions
function autocomplete(val) {
var people_return = [];
for (i = 0; i < people.length; i++) {
if (val === people[i].slice(0, val.length)) {
people_return.push(people[i]);
}
}
return people_return;
}
// events
input.onkeyup = function(e) {
input_val = this.value;
if (input_val.length > 0) {
var people_to_show = [];
autocomplete_results = document.getElementById("autocomplete-results");
autocomplete_results.innerHTML = '';
people_to_show = autocomplete(input_val);
for (i = 0; i < people_to_show.length; i++) {
autocomplete_results.innerHTML += '<li>' + people_to_show[i] + '</li>';
}
autocomplete_results.style.display = 'block';
} else {
people_to_show = [];
autocomplete_results.innerHTML = '';
}
}
<div id="autocomplete-container">
<input type="text" autofocus="true" name="autofocus sample" placeholder="search people" id="autocomplete-input"></input>
<ul id="autocomplete-results">
</ul>
</div>
我的问题是:(这是为了理解流程 - 我是Javascript的新手)
答案 0 :(得分:1)
答案 1 :(得分:1)
如果为尚未声明的变量赋值,它将自动成为全局变量。
对于自动完成功能,它通过以下方式调用:
people_to_show = autocomplete(input_val);
autocomplete()
的返回值是分配给people_to_show
input_val
来自this.value
,其中this
是输入元素。传递给函数的e
未被代码使用,但您可以像e.target.value
一样使用它。无论如何,事件都会被传递,您可以使用event.target.value
。请参阅我删除e
的代码。
results
// variables
var input = document.querySelector('#autocomplete-input');
var people = ['john doe', 'maria', 'paul', 'george', 'jimmy'];
var results;
// functions
function autocomplete(val) {
var people_return = [];
for (i = 0; i < people.length; i++) {
if (val === people[i].slice(0, val.length)) {
people_return.push(people[i]);
}
}
return people_return;
}
// events
input.onkeyup = function() {
input_val = event.target.value;
if (input_val.length > 0) {
var people_to_show = [];
autocomplete_results = document.getElementById("autocomplete-results");
autocomplete_results.innerHTML = '';
people_to_show = autocomplete(input_val);
for (i = 0; i < people_to_show.length; i++) {
autocomplete_results.innerHTML += '<li>' + people_to_show[i] + '</li>';
}
autocomplete_results.style.display = 'block';
} else {
people_to_show = [];
autocomplete_results.innerHTML = '';
}
}
<div id="autocomplete-container">
<input type="text" autofocus="true" name="autofocus sample" placeholder="search people" id="autocomplete-input"></input>
<ul id="autocomplete-results">
</ul>
</div>