Javascript 选择下拉菜单 onchange 未正确触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4048406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:15:26  来源:igfitidea点击:

Javascript select drop down menu onchange not firing properly

javascriptonchange

提问by Ross Larson

my onchange isn't firing the javascript method properly.

我的 onchange 没有正确触发 javascript 方法。

Select code (in HTML file)

选择代码(在 HTML 文件中)

<select id="crit_1" onchange="crit1Update()">
    <option value=null>Criteria 1</option>
 <option value="major">Major</option>
 <option value="grad">Graduation Year</option>
</select>

crit1Update() code (in external filter.js file in same folder as HTML file containing the above with the following code in head of HTML

crit1Update() 代码(在与包含上述内容的 HTML 文件相同的文件夹中的外部 filter.js 文件中,在 HTML 的头部包含以下代码

<script type="text/javascript" src="filter.js">
</script>

function crit1Update() {
 var crit1 = document.criteria.getElementsByID("crit1");
 var criteria1 = crit1.options[crit1.selectedIndex].value;
 alert("criteria1"); // this is never firing, so this isnt getting called
 if (criteria1 == null) {
  // eventually set all other lists to null in here as well
  filter(null,null,null,null,null,null)
            // the above returns all the resumes 
            // (this is eventually going to filter resumes)
 }
 else if (criteria1 == "major") {
  alert("Major!");
 }
}

Are there any glaring or not glaring errors that I am missing? I dont see why the alert("criteria1" isnt being called. I come from a java background and this is my first foray into JS, so I may be missing something simple.

有没有我遗漏的明显或不明显的错误?我不明白为什么 alert("criteria1" 没有被调用。我来自 java 背景,这是我第一次涉足 JS,所以我可能会遗漏一些简单的东西。

Thanks for any help.

谢谢你的帮助。

回答by scunliffe

There is a typo in this method call:

这个方法调用中有一个错字:

document.criteria.getElementsByID(

should be

应该

document.criteria.getElementById(
                            ^  ^ no "s" and lower case "d"

also make sure the id matches your HTML element e.g. "crit_1"

还要确保 id 与您的 HTML 元素匹配,例如“crit_1”

回答by Phil

Your <select>ID is "crit_1" and your function is looking for ID "crit1" (no underscore).

您的<select>ID 是“crit_1”,您的函数正在寻找 ID“crit1”(无下划线)。

It would probably be a better idea to pass the <select>element as a reference to the function, eg

<select>元素作为对函数的引用传递可能是一个更好的主意,例如

JavaScript

JavaScript

function crit1Update(crit1) {
    var criteria1 = crit1.options[crit1.selectedIndex].value;

HTML

HTML

<select id="crit1" name="crit1" onchange="crit1Update(this)">