我是新的javascript和有问题时玩w3学校的例子。下面是来自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部件,并使用css显示属性使其由html完成。
发布于 2022-05-14 12:45:20
当应用您所做的更改时,您的代码不能工作的原因是,函数closeAllLists()删除了任何具有类名autocomplete-items的元素,还删除了包含所有自动完成元素的div。
我对您的代码进行了一些更改以使其工作:
在html中,我给了您的div一个autocomplete-items-container id。
<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?
祝你学习之旅好运!希望这有点帮助。
https://stackoverflow.com/questions/72239065
复制相似问题