我的应用程序动态添加了下拉列表。用户可以添加任何他们需要的数量。
我传统上使用jQuery的live()方法来检测当这些下拉列表被更改()时:
$('select[name^="income_type_"]').live('change', function() {
alert($(this).val());
});
从jQuery 1.7开始,我将其更新为:
$('select[name^="income_type_"]').on('change', function() {
alert($(this).val());
});
查看文档,这应该是完全有效的(对吧?)-但事件处理程序从未触发。当然,我已经确认jQuery 1.7已经加载并运行,等等。错误日志中没有错误。
我做错了什么?谢谢!
on文档声明(粗体;)):
事件处理程序仅绑定到当前选定的元素;在代码调用.on()时,它们必须存在于页面上。
与.live()等价的是
$(document.body).on('change', 'select[name^="income_type_"]', function() {
alert($(this).val());
});
不过,最好将事件处理程序绑定到尽可能靠近元素的地方,也就是说,绑定到层次结构中更接近的元素。
更新:在回答另一个问题时,我发现.live文档中也提到了这一点:
根据.live()方法的继承者重写它很简单;下面是三个事件附件方法等价调用的模板:
美元(选择器)。Live(事件、数据、处理程序);jQuery 1.3+
$(document).delegate(选择器,事件,数据,处理程序);jQuery 1.4.3+
美元(文档)。On(事件,选择器,数据,处理器);// jQuery 1.7+
除了选定的答案,
端口jQuery。在等待应用程序迁移到jQuery 1.9+时。将其添加到JavaScript文件中。
// Borrowed from jQuery 1.8.3's source code
jQuery.fn.extend({
live: function( types, data, fn ) {
if( window.console && console.warn ) {
console.warn( "jQuery.live is deprecated. Use jQuery.on instead." );
}
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}
});
注意:以上函数在jQuery v3中不能工作。选择器被移除。
或者,您可以使用https://github.com/jquery/jquery-migrate
jquery版本x.x.x.js打开编辑器,找到jquery .fn.extend
添加代码
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
示例:jquery-2.1.1.js——> line 7469 (jQuery.fn.extend)
示例图像视图