Javascript onchange 选择不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7933053/
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
Javascript onchange select not working
提问by JaredPar
I'm trying to create an onchange event using javascript on a select element. But its not working, any hint what I'm doing wrong?
我正在尝试在选择元素上使用 javascript 创建一个 onchange 事件。但它不起作用,任何暗示我做错了什么?
Script..
脚本..
<script type="text/javascript">
function check() {
alert("Hi");
}
</script>
HTML..
HTML..
<body>
<select name="selTitle" id="titles" onchange="check();">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
</body>
Demo - http://jsfiddle.net/jq9UA/1/
回答by JaredPar
The problem in the Fiddle is that the JavaScript code is running in response to the window load event (default on fiddle). Any code you run is defined in the context of the load call back and not at the global scope. If you look through the actual generated HTML for the frame you will find it looks like this
小提琴中的问题是 JavaScript 代码正在运行以响应窗口加载事件(小提琴上的默认值)。您运行的任何代码都是在加载回调的上下文中定义的,而不是在全局范围内定义的。如果您查看为框架实际生成的 HTML,您会发现它看起来像这样
$(window).load(function(){
function check() {
alert("Hi");
}
});
This means your code defines a check
function which is local to the load callback but the event handler wants to invoke a globally defined check
function.
这意味着您的代码定义了一个check
加载回调本地的函数,但事件处理程序想要调用一个全局定义的check
函数。
To fix this you need to use one of the fiddle settings that defines the JavaScript in a global context. Try "no wrap (head)".
要解决此问题,您需要使用在全局上下文中定义 JavaScript 的小提琴设置之一。尝试“不包裹(头)”。
Fiddle: http://jsfiddle.net/jq9UA/3/
回答by Mechkov
I have tested this and works perfectly fine:
我已经测试过这个并且工作得很好:
<script name="text/javascript">
function check() {
alert("Hi");
}
</script>
<body>
<select name="selTitle" id="titles" onchange="check();">
<option value="Mr." value="1">Mr.</option>
<option value="Ms." value="2">Ms.</option>
</select>
</body>