调用下拉列表的 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

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

call javascript function onchange event of dropdown list

javascripthtml

提问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/

小提琴:http: //jsfiddle.net/6uyz4b8x/1/

采纳答案by SilentTremor

Your code is working just you need to declare your javscript method before DOM ready.

您的代码正在运行,只是您需要在 DOM 准备好之前声明您的 javscript 方法。

your working example

你的工作示例

回答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

using jQuery

使用 jQuery

 $("#ddl").change(function () {
                alert($(this).val());
            });

jsFiddle

js小提琴

回答by Dinesh.net

You just try this, Its so easy

你试试这个,太简单了

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

回答by bemol

jsFunction is not in good closure. change to:

jsFunction 没有很好的关闭。改成:

jsFunction = function(value)
{
    alert(value);
}

and don't use global variables and functions, change it into module

并且不要使用全局变量和函数,改成模块