gpt4 book ai didi

javascript - 下拉菜单减少全局变量范围

转载 作者:行者123 更新时间:2023-11-28 04:58:01 25 4
gpt4 key购买 nike

如何将全局“x”变量的范围缩小为局部变量?请注意,简单地将“var x”移动到“showAddress”函数中是行不通的,因为 keyup 事件监听器会将变量重置为 0 evetytime。如有任何帮助,我们将不胜感激。

document.getElementById("where").addEventListener("keyup", showAddress, false);

var x = 0;

function showAddress (e) {

var search = document.getElementById("where").value;
if (search.length < 2) {
document.getElementById("addressNav").innerHTML = '';
return 0;
} else {
var hr = new XMLHttpRequest();
var url = "/handlers/suggestAddress.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
document.getElementById("addressNav").innerHTML = hr.responseText;


// click on the address
var divs = document.getElementById("addressNav").getElementsByTagName("div"), i;
for (i = 0; i < divs.length; i++) {
divs[i].onclick = function () {
document.getElementById("where").value = this.innerHTML;
document.getElementById("addressNav").innerHTML = '';
};
}

//navigate address from keyboard
if (e.keyCode == 38) {
if (x > 0) {
x -= 1;
} else {
x = divs.length - 1;
}
} else if (e.keyCode == 40) {
if (x < divs.length - 1) {
x += 1;
} else {
x = 0;
}
} else {
if (e.keyCode == 13) {
document.getElementById("where").value = divs[x].innerHTML;
document.getElementById("addressNav").innerHTML = '';
}
}

divs[x].setAttribute("class", "addressListKeyboard");
console.log(x);
}
};
hr.send("search=" + search);
}
}

最佳答案

变量 x 应该记住最后选择的 div,这就是它具有全局范围的原因。将其移动到本地范围将不起作用,因为 showAddress 是 keyup 事件处理程序,每次发生 keyup 事件时都会删除 x 的值。

关于javascript - 下拉菜单减少全局变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42381422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com