Javascript HTML <select> JQuery .change 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11216192/
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
HTML <select> JQuery .change not working
提问by theCamburglar
Alright I don't see why this isnt working. It seems pretty simple.
好吧,我不明白为什么这不起作用。看起来很简单。
Here is my drop-down menu:
这是我的下拉菜单:
<div>
<form>
<select id='yearDropdown'>
<c:forEach var="years" items="${parkYears}">
<option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option>
</c:forEach>
</select>
</form>
</div>
and here is the JavaScript
这是 JavaScript
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});
Right now I just want to get it working so I can add functionality. Thanks!
现在我只想让它工作,这样我就可以添加功能。谢谢!
回答by xandercoded
That code is syntactically correct. Most likely running it at the wrong time.
该代码在语法上是正确的。很可能在错误的时间运行它。
You'll want to bind the event when the DOM is ready:
当DOM 准备好时,您需要绑定事件:
$(function(){ /* DOM ready */
$("#yearDropdown").change(function() {
alert('The option with value ' + $(this).val());
});
});
Or, use live
:
或者,使用live
:
$("#yearDropdown").live('change', function() {
alert('The option with value ' + $(this).val());
});
Or, use delegate
:
或者,使用delegate
:
$(document.body).delegate('#yearDropdown', 'change', function() {
alert('The option with value ' + $(this).val());
});
Or, if you're using jQuery 1.7+
:
或者,如果您使用的是 jQuery 1.7+
:
$("#yearDropdown").on('change', function() {
alert('The option with value ' + $(this).val());
});
Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.
尽管如此,通常最好在浏览器完成标记渲染后执行脚本。
回答by Alberto De Caro
I have tried your code in jsFiffle. I manually added some years as options. It works right.
我已经在 jsFiffle 中尝试过你的代码。我手动添加了一些年份作为选项。它工作正常。
Just bind the .change event in the $(document).ready:
只需在 $(document).ready 中绑定 .change 事件:
$(document).ready(function(){
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});?
});
回答by Louis B.
Your code is correct and is working for me, see here: http://jsfiddle.net/mobweb/2Skp9/
您的代码是正确的并且对我有用,请参见此处:http: //jsfiddle.net/mobweb/2Skp9/
Are you sure jQuery has been loaded properly?
你确定 jQuery 已经正确加载了吗?
回答by Logard
Not sure if this will help, but you could try this:
不确定这是否有帮助,但你可以试试这个:
$("#yearDropdown").live("change", function () {
alert('The option with value ' + $(this).val());
});