下拉时的jQuery change事件 [英] jQuery change event on dropdown
问题描述
我刚刚将查询库添加到我的Web应用程序中,并通过简单的警报进行了测试:
I just added the query lib to my web app and tested with simple alert:
<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
$(function(){
alert('jquery is working');
});
</script>
工作正常.但是,当我想在下拉菜单中实现更改"事件
And works fine. However when i want to implement an "change" event on my dropdown
<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
$("#projectKey").change(function() {
alert($('option:selected', $(this)).text());
});
</script>
它没有显示警报,基本上没有任何反应.我的下拉列表如下:
it displays me no alert, basically nothing is happening. My drop down is the following:
<select id="projectKey" name="projectKey">
<option value="AM">AM</option>
<option value="AIL">AIL</option>
<option value="NEB">NEB</option>
<option value="SSP">SSP</option>
</select>
当然,我尝试简化javascript,只是
Of course i tried to simplify the javascript, just o have
$("#projectKey").change(function() {
alert("test");
});
但仍然没有喜悦.选择器或下拉菜单将有所不同.也尝试过"select#projectKey",但结果当然是相同的.知道我在做什么错吗?
but still no joy. It will be something with the selector or the drop down. Tried also "select#projectKey" but the result was of course the same. Any idea what i am doing wrong?
推荐答案
您应该保留该DOM ready函数
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
如果您在DOM中的元素之前添加了javascript,则文档尚未准备好,您必须使用DOM ready函数或在元素之后添加javascript,通常的位置就在</body>
标记之前
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body>
tag
这篇关于下拉时的jQuery change事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!