使用 jQuery 绑定到动态创建的下拉列表中的更改事件
我正在使用 jQuery 动态创建多个下拉列表。我希望能够在选定的下拉列表项更改时触发事件。从这里和其他地方浏览我发现不可能使用 live() 绑定到下拉列表的更改事件,所以我想知道有什么替代方案?我知道可以绑定到单击事件,但由于该事件发生在下拉列表选择可以更改之前,因此对于跟踪所选项目是否已更改对我来说没有用。
这是我的代码的相关部分。单击任何下拉列表时都会触发警报,但当然我更希望仅在更改所选项目时才触发警报。
$(document).ready(function() {
// Stuff omitted.
addEventHandlers();
}
function addEventHandlers() {
// Stuff omitted.
$('#divReview select').live("click", function(){
alert('This is where I would like the change event to occur instead.');
});
}
I am creating a number of dropdown lists dynamically using jQuery. I would like to be able to trigger an event when the selected dropdown list item changes. From browsing on here and elsewhere I see that it's not possible to bind to the change event of the dropdown lists using live() so I am wondering what are the alternatives? I know it's possible to bind to the click event but since that occurs before the dropdown list selection can change it's no use to me for tracking if the selected item has changed.
This is the relevant part of my code. The alert triggers when any of the dropdown lists are clicked on but of course I would prefer if the alert was triggered only when the selected item is changed.
$(document).ready(function() {
// Stuff omitted.
addEventHandlers();
}
function addEventHandlers() {
// Stuff omitted.
$('#divReview select').live("click", function(){
alert('This is where I would like the change event to occur instead.');
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
change
事件而不是click
,如下所示:之前 IE 中存在一个错误jQuery 1.4.2 发布。在此之前,
change
在 IE 中无法正确冒泡(.live( )
依赖),这个问题在 1.4.2 中得到了修复,所以如果使用该版本或更高版本,这应该可以工作。Use the
change
event instead ofclick
, like this:There was a bug in IE specifically before the jQuery 1.4.2 release. Before then,
change
didn't bubble correctly in IE (which.live()
relies on), this was fixed in 1.4.2, so if using that version or higher, this should work.经过一番搜索后,我遇到了 this 问题,这似乎是一个类似的问题。我将 jQuery 方法更改为此,它在 IE8 上按预期工作:
After a bit of searching I came across this question which seems to be a similar issue. I changed my jQuery method to this and it works as expected on IE8: