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

时间:2015-07-30 21:37:15

标签: javascript html list syntax external

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

(对不起,如果这个问题已经存在,但我无法找到)

2 个答案:

答案 0 :(得分:1)

问题是找不到 search01 。该元素称为 SearchFail01 。由于search01不存在,getElementById会返回null。设置null.innerHTML失败,因此有效地,数据主义者永远不会添加到文档中。

如果您在JavaScript代码中使用 SearchFail01 (或任何其他现有ID)替换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>

答案 1 :(得分:0)

您刚刚没有使用正确的ID:&#34; bar&#34;。 ;)

&#13;
&#13;
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;
  }
}
&#13;
<input type='search' id='bar' list='countries' placeholder='Search for a country..' onkeydown='keyEnter(event);' />

<p id="SearchFail01"></p>
&#13;
&#13;
&#13;