【发布时间】:2026-02-03 11:50:01
【问题描述】:
我在 javascript 中使用客户端搜索栏已经有一段时间了,我有一个 <datalist>,其中包含 JavaScript 中的所有选项。
<datalist> 在 document.getElementById("").innerHTML 内。但是搜索栏(<input>)在 html 文件中。而且我厌倦了将输入上的列表语法设置为list="countries",这是数据列表的ID。我不想把整个数据列表放在每个 html 页面中,如果我把它放在 javascript 中,输入就不能正常工作。如果他们不在同一个文件中,他们似乎无法沟通......如果有人可以帮助我,我将非常感激!
它在这里工作,因为它不是外部文件。
代码如下:
document.getElementById("search01").innerHTML =
"<form id='search'><datalist id='countries'>" +
"<option value='Afghanistan'>" +
"<option value='Albania'>" +
"</datalist></form>";
function onSearch() {
var country;
country = document.getElementById('bar').value;
if (country == "Afghanistan" || country == "afghanistan") {
window.location.href = "http://www.example.com/";
} else if (country == "Albania" || country == "albania") {
location.href = "http://www.example.com/";
} else {
document.getElementById("SearchFail01").innerHTML =
"The country '" + country + "' does not exist";
}
}
//check when the enter is pressed on the search bar
function keyEnter(event) {
var key = event.keyCode || event.which;
if (key == 13) {
onSearch();
} else {
return true;
}
}
<input type='search' id='bar' list='countries' placeholder='Search for a country..' onkeydown='keyEnter(event);' />
<p id="SearchFail01"></p>
(对不起,如果这个问题已经存在但我找不到它)
【问题讨论】:
标签: javascript html list syntax external