javascript - javascript setAttribute 替换

我是 javascript 的新手,在玩 w3school 的示例时遇到问题。这是来自 https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_autocomplete 的问题的链接

HTML 的原始示例代码是

<form autocomplete="off" action="/action_page.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="myCountry" placeholder="Country">
  </div>
  <input type="submit">
</form>

以及部分原始样本 javascript

a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {...

而我将 HTML 替换为

<form autocomplete="off" action="/action_page.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="myCountry" placeholder="Country">
    <div class="autocomplete-items" style="display:none"></div>
  </div>
  <input type="submit">
</form>

样式部分我实际上是在 css 样式中完成的。

并将 javascript 更改为

a = document.querySelector(".autocomplete-items");
a.style.display = "block";

替换以下内容并保留原始代码的其余部分。

a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);

我认为结果应该是相同的,但事实证明它不起作用。我的想法有什么问题吗?我想跳过 createElement 部分并通过 html 和 css 显示属性完成。

回答1

应用您所做的更改时您的代码不起作用的原因是因为函数 closeAllLists() 删除了类名为 autocomplete-items 的任何元素,因此也删除了包含所有自动完成元素的 div。

我对您的代码进行了一些更改以使其正常工作:

在 html 中,我给了你的 div 一个 ID 为 autocomplete-items-container

<form autocomplete="off" action="/action_page.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="myCountry" placeholder="Country">
    <div id="autocomplete-items-container"></div>
  </div>
  <input type="submit">
</form>

并在 javascript 中进行了一些更改:

function autocomplete(inp, arr) {
   var a = document.querySelector('#autocomplete-items-container');
   etc.
function closeAllLists(elmnt) {
    var x = document.querySelectorAll("#autocomplete-items-container > *");
    etc.
inp.addEventListener("keydown", function(e) {
      var x = document.querySelector('#autocomplete-items-container');
      etc.

请注意,我建议更改一些变量名称以使代码对您自己更具可读性,特别是如果您是 javascript 新手。

例如,将 a 更改为 container,将 b 更改为 listItem,将 x 更改为 allItems 怎么样?

祝你的学习之旅好运!希望这有点帮助。

相似文章

随机推荐

最新文章