2016-03-15 61 views
1

作为JS和jquery的新角色,我似乎无法让这件事情起作用!该警报提供undefined通过jquery .on()函数将单击元素的属性值传递给外部函数

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); 

显示“测试”。

+1

显示完整的代码?我不明白'this'是什么? – chris97ong

+0

您可以将ID存储在第一行上方的变量中。 var id = $(this).attr('id')。那么你的第三个参数就是{id:id} – walkerrandophsmith

+0

那么,如果使用第二种方法会出现什么问题? –

回答

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); 
} 
0

$(this)在您的非工作版本中是在注册onclick处理程序的函数的上下文中。 'id'未定义,因为它不是当时所处对象的属性,而是将未定义的属性分配给数据对象的id属性。

$(this)在第二个工作版本中是在调用声明函数的元素的上下文中。

谁是'id'attr你想访问?如果它是被点击的对象(我怀疑它),那么你的第二种方法就是你想要实现它的方式,而第一种方法对你的目的是错误的。

+0

Norlihazmey Ghazali的答案解决了我的问题。第一种方法服务于我的目的,因为我想用'id'做更多的事情,而且我不想让on()非常麻烦。 –