HTML <选择>JQuery .change 不起作用 [英] HTML <select> JQuery .change not working
问题描述
好吧,我不明白为什么这不起作用.看起来很简单.
这是我的下拉菜单:
<表格><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>>${年}</c:forEach></选择></表单>
这里是 JavaScript
$("#yearDropdown").change(function () {alert('带有值的选项' + $(this).val());});
现在我只想让它工作,这样我就可以添加功能.谢谢!
该代码在语法上是正确的.很可能在错误的时间运行它.
您需要在 DOM 就绪时绑定事件:
原生 JS/DOM
window.addEventListener('DOMContentLoaded', () => {const yearDropDown = document.getElementById('yearDropdown');yearDropDown.addEventListener('change', () => {警报(yearDropDown.value)});});
jQuery
$(function(){/* DOM 就绪 */$("#yearDropdown").change(function() {alert('带有值的选项' + $(this).val());});});
或者,使用live
:
$("#yearDropdown").live('change', function() {alert('带有值的选项' + $(this).val());});
或者,使用delegate
:
$(document.body).delegate('#yearDropdown', 'change', function() {alert('带有值的选项' + $(this).val());});
或者,如果您使用的是 jQuery 1.7+
:
$("#yearDropdown").on('change', function() {alert('带有值的选项' + $(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:
Native JS/DOM
window.addEventListener('DOMContentLoaded', () => {
const yearDropDown = document.getElementById('yearDropdown');
yearDropDown.addEventListener('change', () => {
alert(yearDropDown.value)
});
});
jQuery
$(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 <选择>JQuery .change 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!