HTML< select> JQuery .change不工作 [英] HTML <select> JQuery .change not working

查看:99
本文介绍了HTML< select> JQuery .change不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我不明白为什么这不工作。看起来很简单。



这是我的下拉菜单:

 < DIV> 
< form>
< select id ='yearDropdown'>
< c:forEach var =年items =$ {parkYears}>
< option value = / events.html?display_year = $ {years}< c:if test =$ {currentYear == years}> selected =selected< / c:if> > $ {年}< /选项>
< / c:forEach>
< / select>
< / form>
< / div>

这里是JavaScript

 $(#yearDropdown)。change(function(){
alert('该值为'+ $(this).val());
} );

现在我只想让它工作,所以我可以添加功能。谢谢!

解决方案

该代码在语法上是正确的。很可能在错误的时间运行它。



DOM准备就绪时,您需要绑定该事件

  $(function(){/ * DOM ready * / 
$(#yearDropdown b $ b alert('value'+ $(this).val());
});
});

或使用直播

  $(#yearDropdown)。live('change',function(){
alert(' '+ $(this).val());
});

或使用委托

  $(document.body).delegate('#yearDropdown','change',function(){
alert值为+ $(this).val());
});

或者,如果您使用jQuery 1.7 +

  $(#yearDropdown)。on('change',function(){
alert ('value'+ $(this).val());
});






尽管如此,通常最好执行一次脚本浏览器已经完成渲染标记。


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

$("#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!

解决方案

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:

$(function(){ /* DOM ready */
    $("#yearDropdown").change(function() {
        alert('The option with value ' + $(this).val());
    });
});

Or, use live:

$("#yearDropdown").live('change', function() {
    alert('The option with value ' + $(this).val());
});

Or, use delegate:

$(document.body).delegate('#yearDropdown', 'change', function() {
    alert('The option with value ' + $(this).val());
});

Or, if you're using 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.

这篇关于HTML&lt; select&gt; JQuery .change不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆