简体   繁体   中英

How to get “this” on click element in OOP JavaScript

I have the following bit of JS:

bindEvents: function() {
  this.extra.bind("click", {context: this}, this.checkPackage.bind(this));
},
checkPackage: function(e) {
  console.log(e.data.context);
}

What I want is the checkPackage method to be like $(this).whatever , but I can't seem to access the clicked object. It just selects a the first object from the DOM with the this.extra class. How could I make this work?

Try e.currentTarget for the object, where the eventlistener is attached to. e.target will give u the actual clicked object (could be different).

You can try e.target to get the clicked element.

bindEvents: function() {
  this.extra.bind("click", {context: this}, this.checkPackage.bind(this));
},
checkPackage: function(e) {
  console.log(e.target);
}

You can refer jQuery event docs , but summary as follows:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

In your case .you can use below code

bindEvents: function() {
  this.extra.bind("click", {context: this}, this.checkPackage.bind(this));
},
checkPackage: function(e) {
  console.log(e.currentTarget);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM