调用下拉列表的 javascript 函数 onchange 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26709969/
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
call javascript function onchange event of dropdown list
提问by Shaggy
I want to invoke javascript function when value in the dropdown list changes. I dont want to hardcode dropdown list id.
我想在下拉列表中的值更改时调用 javascript 函数。我不想硬编码下拉列表 id。
Hence not using document.getElementById
因此不使用 document.getElementById
My Code:
我的代码:
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
function jsFunction(value)
{
alert(value);
}
This is giving error ReferenceError: jsFunction is not defined
这是给错误 ReferenceError: jsFunction is not defined
Fiddle : http://jsfiddle.net/6uyz4b8x/1/
采纳答案by SilentTremor
Your code is working just you need to declare your javscript method before DOM ready.
您的代码正在运行,只是您需要在 DOM 准备好之前声明您的 javscript 方法。


回答by Bartek Andrzejczak
I don't know why do you need this onmousedownevent here, but what you have to do is put your function above actual usage. Look at the snipplet below:
我不知道你为什么需要这个onmousedown事件,但你要做的就是把你的函数放在实际使用之上。看看下面的片段:
<script type="text/javascript">
function jsFunction(value)
{
alert(value);
}
</script>
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
回答by Alex
回答by Dinesh.net
You just try this, Its so easy
你试试这个,太简单了
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>

