作为JS和jquery的新来者,我似乎无法让这件事工作!警报提供undefined
!
this.$el.on('click', '.chorse-item',{id:$(this).attr('id')}, this.handleItem);
this.handleItem = function(event) {
alert(event.data.id);
}
它与
完美地显示“id”this.$el.on('click', '.chorse-item', function(){alert($(this).attr('id'))});
我怀疑$(this).attr('id')
超出了范围或什么?原因
this.$el.on('click', '.chorse-item',{id:"Testing"}, this.handleItem);
显示“测试”。
答案 0 :(得分:0)
$(this)在你的非工作版本中是在注册onclick处理程序的函数的上下文中。 'id'未定义,因为它不是您当时所在对象的属性,而是将该未定义属性分配给数据对象的id属性。
$(this)在第二个工作版本中是在调用声明函数的元素的上下文中。
你想要访问谁是'id'at?如果它是被点击的对象(我怀疑),那么你的第二种方法是你想要实现它的方式,并且第一种方法对你的目的是错误的。
答案 1 :(得分:0)
无需在.on
方法中传递任何数据,因为它在调用函数中已经可用:
this.$el.on('click', '.chorse-item', this.handleItem );
this.handleItem = function(event) {
// `this` here != with the this `this.handleItem`
// this here would refer to this `.chorse-item` already
// so just calling it using `this.id` or `$( this ).attr( 'id' )`
// in order to get clicked element's id or anything else related
alert(this.id);
}