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

时间:2017-02-22 02:06:50

标签: javascript php ajax

如何将全局“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);
    }
}

1 个答案:

答案 0 :(得分:0)

变量x应记住最后选择的div以及它具有全局范围的原因。将其移动到本地作用域将不起作用,因为showAddress是键盘事件处理程序,它将在每次键盘事件发生时擦除x的值。