用JavaScript生成下拉列表(未知错误)

Generate dropdown List in JavaScript (unknown mistake)

本文关键字:未知 错误 下拉列表 JavaScript      更新时间:2023-09-26

每次用户更改List1(selQueryType)中的选择时,我都要重新生成List2。在其原始状态下,List2空白。这两个列表都是较大的HTML输入文档的一部分List1有4个选项,所以最终会有4个if——实际上是一个switchList2是从预定义的数组(listvalues)生成的,而不是从List1生成的(请参阅代码)。

Function QueryTypeChg()onchange List1触发-我用警报检查过,它被触发了。当尝试生成List2的新选项时,问题似乎出现在for周期中没有向List2添加任何选项,它与原来一样保持空白。

function QueryTypeChg()
{
var selIndex = document.getElementById("selQueryType").selectedIndex;
var objSel = document.getElementById("selSortt");
var i = 0;
while (objSel.length > 0)
   {
   objSel.remove(0);
   }
if (selIndex == 0)
   {
   var listvalues = ["Species", "Region, area", "Anthesis", "Vulnerability"];
   for (i = 0; i < options.length; i++) 
       {
       var option = document.createElement("option");
       option.text = listvalues[i];
       option.value = i;       
//       alert("option.text is " + option.text);
       objSel.add(option);
       }​
   }

}

因为您通过执行来移除元素

while (objSel.length > 0)
{
  objSel.remove(0);
}

如果你想清除选择,只需将while循环替换为

objSel.innerHTML = "";

完整代码应为

function QueryTypeChg()
{
  document.getElementById("selSortt").innerHTML = document.getElementById("selQueryType").innerHTML 
  document.getElementById("selSortt").selectedIndex = document.getElementById("selQueryType").selectedIndex;
}

您可以使用选项变量,而不是列表值请更改以下代码,这可能有助于

 for (i = 0; i < options.length; i++) 

带有

for (i = 0; i < listvalues.length; i++) 

我用以下代码"钉住"了它:

function QueryTypeChg()
{
var selIndex = document.getElementById("listQueryType").selectedIndex;
localStorage.setItem("QueryType", selIndex);
if (selIndex == 0)
   {
   var listvalues = ["Species", "Region, area", "Anthesis", "Vulnerability"];
   var str_options = '';
   for (var i=0; i < listvalues.length; i++)
       {
       str_options += "<option value='" + [i] + "'>" + listvalues[i] + "</option> 'r'n";
       }
   $("#listSort").html("");
   $("#listSort").append(str_options);
   return;
   }
}

我仍然不知道为什么它不适用于最初的代码。它在W3Schools Try It窗口和我看到的其他例子中确实有效。还有一个特别之处是它使用了html()方法,而不是innerHTML属性。无论如何,这个JavaScript是一种什么样的通用语言?在Pascal中,做某件事总是只有一种方法!