我如何在Ajax调用和事件处理程序中操作DOM

时间:2018-11-06 09:36:51

标签: javascript ajax autocomplete

我有一个基于this示例的自动填充功能。

在我的解决方案中,我想将countrys数组交换为一个由ajax调用提供服务的数组。这些项目已正确加载并显示,但是keydown事件和css类的操作未完成或未显示。这是我的代码:

编辑:尝试弄清楚我的问题:链接的示例适用于已定义国家/地区的数组,这些国家/地区已作为参数添加到自动完成功能中。但是,我希望从rest服务创建数组,该服务将由ajax调用进行调用。

我的问题是,在事件'KEY DOWN'上,这些项没有按照div项的建议进行突出显示(请参见方法addActiv())。

我不确定问题出在哪里。在事件监听器中进行ajax调用会不会有问题?

<script>
function autocomplete(inp) {

            var currentFocus;
            /*execute a function when someone writes in the text field:*/
            inp.addEventListener("input", function(e) {
                var a, b, i, val = this.value;
                if (!val) {
                    return false;
                }
                currentFocus = -1;
                a = document.createElement("DIV");
                a.setAttribute("id", this.id + "autocomplete-list");
                a.setAttribute("class", "autocomplete-items");

                this.parentNode.appendChild(a);
                $.ajax({
                    url : 'http://localhost:8080/find/' + val.toLowerCase(),
                    dataType : 'json',
                    type : 'GET',
                    success : function(data) {
                        if (data) {
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
                                    b = document.createElement("DIV");
                                    b.innerHTML = "<strong>" + data[i].substr(0, val.length) + "</strong>";
                                    b.innerHTML += data[i].substr(val.length);
                                    b.innerHTML += "<input type='hidden' value='" + data[i] + "'>";

                                    b.addEventListener("click", function(e) {
                                        inp.value = this.getElementsByTagName("input")[0].value;
                                        closeAllLists();
                                    });
                                    a.appendChild(b);
                                }
                            }
                        }
                        //e.preventDefault();
                        return false;
                    },
                    error : function() {
                        console.log('Error call for '+ url);
                    }
                });//end ajax
            });//end addEventListener


            /*execute a function presses a key on the keyboard:*/
            inp.addEventListener("keydown", function(e) {
                    var x = document.getElementById(this.id + "autocomplete-list");
                  if (x){
                      x = x.getElementsByTagName("div");
                  } 
                  if (e.keyCode == 40) {
                    /*If the arrow DOWN key is pressed,
                    increase the currentFocus variable:*/
                    currentFocus++;
                    //console.log("currentfocus: " + currentFocus + " " + x[currentFocus].classList);
                    /*and and make the current item more visible:*/
                    addActive(x);
                  } else if (e.keyCode == 38) { //up
                    /*If the arrow UP key is pressed,
                    decrease the currentFocus variable:*/
                    currentFocus--;
                    /*and and make the current item more visible:*/
                    addActive(x);
                  } else if (e.keyCode == 13) {
                    /*If the ENTER key is pressed, prevent the form from being submitted,*/
                    e.preventDefault();
                    if (currentFocus > -1) {
                      /*and simulate a click on the "active" item:*/
                      if (x) x[currentFocus].click();
                    }
                  }
            });

            function addActive(x) {
                /*a function to classify an item as "active":*/
                if (!x) return false;
                /*start by removing the "active" class on all items:*/
                removeActive(x);
                if (currentFocus >= x.length){
                    currentFocus = 0;
                }
                if (currentFocus < 0) {
                    currentFocus = (x.length - 1);
                }
                /*add class "autocomplete-active":*/
                x[currentFocus].classList.add("autocomplete-active");
            }

            function removeActive(x) {
                /*a function to remove the "active" class from all autocomplete items:*/
                for (var i = 0; i < x.length; i++) {
                  x[i].classList.remove("autocomplete-active");
                }
            }

            function closeAllLists(elmnt) {
                /*close all autocomplete lists in the document,
                except the one passed as an argument:*/
                var x = document.getElementsByClassName("autocomplete-items");
                console.log('cloasAllList');
                for (var i = 0; i < x.length; i++) {
                    if (elmnt != x[i] && elmnt != inp) {
                        x[i].parentNode.removeChild(x[i]);
                    }
                }
            }
            /*execute a function when someone clicks in the document:*/
            document.addEventListener("click", function (e) {
                closeAllLists(e.target);
            });
        }


        autocomplete(document.getElementById("myInput"));
       </script>

我不确定它是否可以与事件处理程序中的ajax调用一起使用,或者我是否需要单独调用ajax。在控制台中记录输出可正确显示按下键的触发,但div中的项目未突出显示。

我该如何更正代码?

1 个答案:

答案 0 :(得分:0)

问题已解决。 问题是ajax调用不断添加列表,导致大量带有无效引用的div元素。在ajax调用之前清理列表并创建div元素即可解决问题。