如何將全局「x」變量的範圍縮小到局部變量? 請注意,僅僅在「showAddress」函數內移動「var x」將不起作用,因爲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);
}
}
對不起,但您在這裏想要問的問題是什麼? –
「var x」目前被聲明爲全局的,代碼有效,但是它僅用於「showAddress」函數,因此我想將「var x」範圍從全局範圍縮小到本地範圍。 – Swartz
爲什麼-1? – Swartz