为什么addEventListener不在更改时触发?

Why won't the addEventListener trigger on change?

本文关键字:addEventListener 为什么      更新时间:2023-09-26

试图让事件监听器运行,即当我选择英国时,另一个选择框将出现选择县(县()函数),但由于某种原因,addEventListener不会调用该函数,我无法理解如何将选定的国家传递给县函数?有什么想法吗?

                function countries() {
                    xmlRequest("countries.xml");
                    var country_selector = document.createElement("SELECT");
                    country_selector.id = "cou n tryselection";
                    document.getElementById("quiz").appendChild(country_selector);
                    var t = document.getElementById("countryselection");
                    var c_opt = document.createElement("option");
                    c_opt.text = "Please select";
                    c_opt.selected = true;
                    t.add(c_opt);
                    c_opt = document.createElement("option");
                    c_opt.text = "United Kingdom";
                    c_opt.value = "1";
                    t.add(c_opt);
                    document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
                    var x = xmlDoc.getElementsByTagName("country");
                    for (i = 0; i < x.length; i++) {
                        var opt = document.createElement("option");
                        opt.text = x[i].getElementsByTagName("country_name ")[0].childNodes[0].nodeValue;
                        t.add(opt);
                    }
                }
                function county(Country) {
                    if (!document.getElementById("countyselection")) {
                        if (Country === "1") {
                            xmlRequest("counties.xml");
                            document.getElementById("quiz").innerHTML += "<select id='countyselection'></select>";
                            var t = document.getElementById("countyselection");
                            var y = xmlDoc.getElementsByTagName("county");
                            for (j = 0; j < y.length; j++)
                            {
                                var opt = document.createElement("option");
                                var txt = y[j].getElementsByTagName("county_name")[0].childNodes[0].nodeValue;
                                opt.text = txt;
                                t.add(opt);
                            }
                        }
                    } else {
                        var f = document.getElementById("countyselection");
                        document.getElementById("countyselection").parentNode.removeChild(f);
                    }
                }

因为你是在调用函数,而不是引用它,而且你在函数名中有一个空格。

改变
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);

document.getElementById("countryselection").addEventListener("change", function() {
    county(this.value);
}, false);

还要注意像这样的事情

country_selector.id = "cou n tryselection";

是完全无效的,你不能使用带有空格的随机文本作为ID

相关文章:
  • 没有找到相关文章