Reputation: 989
I dynamically add elements with class .footprint
to DOM and need to add click()
event to them. My current code looks like this:
$("#pcb").on("click", ".footprint", selectFootprint);
However, selectFootprint(sender)
method has a parameter where I would like to pass DOM element (this).
How can I do it?
Upvotes: 1
Views: 2193
Reputation: 235
Instead of using selectFootprint directly as a callback, define a new function that calls selectFootprint with this as parameter (this inside an eventlistener always refers to the DOM element the listener is attached to)
$(".footprint").on("click", function() {
selectFootprint(this);
});
Upvotes: 1
Reputation: 2377
Acutely, in on() jQuery function- this
keyword is represent the clicked element, so you can call the function as you wished.
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
(From the decomention).
Or in youre case:
function selectFootprint(){
console.log( $( this ).text() );
}
$("#pcb").on("click", ".footprint", selectFootprint);
Upvotes: 1
Reputation: 138267
A few solutions (to pass the parents context):
1) using jquerys data parameter:
$("#pcb").on("click", ".footprint", this, function(e){
console.log(this, e.data);//data is the parents this
});
2) using a closure
var sender = this;
$("#pcb").on("click", ".footprint", function(){
selectFootprint.call(this, sender);
});
Or if you just want to pass the .footprint
:
$("#pcb").on("click", ".footprint",function(){
selectFootprint(this);
});
Upvotes: 3