As a new comer to JS and jquery, I just can't seems to get this thing working! The alert gives undefined
!
this.$el.on('click', '.chorse-item',{id:$(this).attr('id')}, this.handleItem);
this.handleItem = function(event) {
alert(event.data.id);
}
It shows the "id" perfectly with
this.$el.on('click', '.chorse-item', function(){alert($(this).attr('id'))});
I suspect the $(this).attr('id')
is falling out of scope or something? cause
this.$el.on('click', '.chorse-item',{id:"Testing"}, this.handleItem);
Shows the "Testing".
$(this) in your non-working version is in the context of the function registering the onclick handler. 'id' is undefined because it's not an attribute of the object you are in at the time, and you are assigning that undefined attribute to the id property of the data object.
$(this) in the second working version is in the context of the element calling the declared function.
Who's 'id' attr are you wanting to get access to? If it's the object that's clicked (which I suspect) then your second method is the way you want to be implementing this, and the first method is wrong for your purpose.
No need to pass any data inside .on
method, as it already available inside the calling function :
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.