【发布时间】:2021-08-09 04:12:33
【问题描述】:
我的 JavaScript 技能非常基础,但我编写了 this 代码,您可以从左侧的下拉列表 (Select1) 中选择一个选项,该选项仅显示右侧下拉列表中的指定选项 (Select2),以及隐藏其余部分。 我还把它放在了代码笔here 中,以防你想摆弄。 该代码似乎在 Firefox 90.0.2 中的上述两种环境中都有效,但在这两种环境中都失败了,并且在 Chrome 92.0.4515.131 中没有向控制台写入任何内容。
知道为什么它可以在 Firefox 中运行,但不能在 Chrome(和其他)中运行,以及我可以做些什么使其适用于所有主要浏览器。
我运行的是 Windows 10,如果可行,我想避免使用 iQuery,因为我还不想学习或使用它,因为我从基础开始。
谢谢。
代码如下:
<!DOCTYPE html>
<html>
<head>
<script>
function hide_options(select_id,type)
{
//alert("hide_options(select_id="+select_id+", type="+type+")");
console.log("hide_options(select_id="+select_id+", type="+type+")");
var x = document.getElementById(select_id);
for (i=1; i<x.options.length; i++)
{
x.options[i].style.display = "none";
}
x.options[0].selected = true;
if (type == 'A')
{ unhide_options(select_id,"one","two") }
if (type == 'B')
{ unhide_options(select_id,"two","three") }
if (type == 'C')
{ unhide_options(select_id,"two") }
}
function unhide_options(select_id,...opts)
{
//alert("unhide_options(select_id="+select_id+"opts="+opts+")");
console.log("unhide_options(select_id="+select_id+"opts="+opts+")");
for (i=0; i<opts.length; i++)
{
document.getElementById(select_id+"_"+opts[i]).style.display = "";
}
}
</script>
</head>
<body>
<p>Selecting an option in the "Select1" dropdown should show only those options in the "Select2" dropdown.</p>
<select name=select1>
<option>Select1...</option>
<option onclick="hide_options('field1','A')">Show options 1 + 2 only</option>
<option onclick="hide_options('field1','B')">Show options 2 + 3 only</option>
<option onclick="hide_options('field1','C')">Show option 2 only</option>
</select>
<select name=update_action id=field1>
<option value=''>Select2...</option>
<option value=one id=field1_one>One</option>
<option value=two id=field1_two>Two</option>
<option value=three id=field1_three>Three</option>
</select>
</body>
</html>
【问题讨论】:
-
最可能的问题是,当单击
<option>时,chrome 无法运行onclick- 您是否尝试过 console.log 在hide_options函数中的运行? -
将
change处理程序添加到select,并重写您的函数以解决此问题
标签: javascript google-chrome firefox