帮助处理下拉菜单上的 jquery onchange 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6090952/
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
help with jquery onchange event on dropdown menu
提问by nunos
I would like to be able to launch an alert message everytime the value of the dropdown is changed. I thought the code below should have worked but it is not for some unknow reason. Any ideas why?
我希望能够在每次更改下拉列表的值时启动警报消息。我认为下面的代码应该可以工作,但不是出于某种未知的原因。任何想法为什么?
Thanks.
谢谢。
<html>
<head>
<script type="text/javascript" src="lib/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$("select").change(function(){
alert(this.id);
});
</script>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
回答by fearofawhackplanet
The code is fine, you just aren't initialising it correctly.
代码很好,只是你没有正确初始化它。
Try....
尝试....
$(document).ready(function() {
$("select").change(function(){
alert(this.id);
});
});
see the documentation here.
请参阅此处的文档。
Your function alerts the id
of the select
element (which you haven't assigned to anything anyway). I'm assuming you actually wanted to get the value from the dropdown? In which case you want:
你的功能提醒id
的的select
元素(你还没有分配到任何东西反正)。我假设您实际上想从下拉列表中获取值?在这种情况下,您想要:
alert($(this).val());
回答by Rob Cowie
Register the onchange handler once the DOM is ready on page load.
一旦 DOM 在页面加载时准备就绪,就注册 onchange 处理程序。
$(function() {
$("select").change(function(event) {
alert(this.id);
// alert( $(this).attr('id') ); to get the id attr with jquery
});
});
I would also suggest targeting the select element with an id. Your code will show an alert every time anyselect on the page is changed.
我还建议使用 id 定位 select 元素。每次更改页面上的任何选择时,您的代码都会显示警报。
回答by Ankit Arjaria
$(document).ready(function(){
$("#projectsName").change(function(){
alert("HI");
});
});
});
Please Note that projectName is the id of dropdown and there is no other id with the same name other wise jquery will not work also double check your jquery plugin
请注意,projectName 是下拉列表的 id,没有其他同名的 id,否则 jquery 将无法工作,也请仔细检查您的 jquery 插件