jQuery On <select> 更改事件不触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11885958/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:02:28  来源:igfitidea点击:

jQuery On <select> Change Event Not Firing

jquery

提问by Dzhuneyt

I have the following in the header:

我在标题中有以下内容:

$('body').on('change', '#userFilter', function(){
   console.log('changed');
});

And this element is dynamically inserted on the page when a tab is clicked:

单击选项卡时,此元素会动态插入到页面上:

<select id="userFilter">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

The problem is that when I change the dropdown nothing is shown in the console.

问题是当我更改下拉菜单时,控制台中没有显示任何内容。

回答by Adil

Wrap it in $(document).ready(function(){....})so that the html control userFilteris added to DOM and available for javascript

将其包裹在$(document).ready(function(){....}) 中,以便将 html 控件userFilter添加到 DOM 中并可用于javascript

$(document).ready(function() {
   $('body').on('change', '#userFilter', function(){
      console.log('changed');
   });
});

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code, jQuery docs.

传递给 .ready() 的处理程序保证在 DOM 准备好后执行,因此这通常是附加所有其他事件处理程序和运行其他 jQuery 代码jQuery docs的最佳位置。

回答by Serj Sagan

Although a bit unrelated to the OQ, if you got here because your select is not firing, make sure that at a previous time you didn't check the "Prevent this page from showing..." in the alert(). You'd need to close the tab and reopen that URL to get that to fire visibly again.

尽管与 OQ 有点无关,但如果您是因为您的选择未触发而来到这里,请确保您之前没有在alert(). 您需要关闭该选项卡并重新打开该 URL 以使其再次可见地触发。