html 列表语法 (list="text") 失败或无法与外部 javascript 文件通信

The html list syntax (list="text") either fails or can't communicate with an external javascript file

我在 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>

(如果这个问题已经存在但我找不到它,我很抱歉)

问题是 search01 没有找到。该元素称为 SearchFail01。因为search01不存在,所以getElementByIdreturnsnull。设置 null.innerHTML 失败,实际上,数据列表永远不会添加到文档中。

如果您在 JavaScript 代码中将 id 替换为 SearchFail01(或任何其他现有的 id),它可以正常工作。

如果您使用开发人员工具 (F12),您可能会发现这一点。控制台显示运行时错误,指出设置 null.innerHTML 无法完成。

document.getElementById("SearchFail01").innerHTML =
  "<form id='search'><datalist id='countries'>" +

  "<option value='Afghanistan'>" +
  "<option value='Albania'>" +
  "</datalist></form>";
<input type='search' id='bar' list='countries' placeholder='Search for a country..' onkeydown='keyEnter(event);' />

<p id="SearchFail01"></p>

您只是没有使用正确的 ID:"bar"。 ;)

document.getElementById("bar").innerHTML =
  "<form id='search'><datalist id='countries'>" +

  "<option value='Afghanistan'>" +
  "<option value='Albania'>" +
  "</datalist></form>";



function onSearch() {
alert(document.getElementById('bar').value);
}

//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>