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?
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);
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);
});
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);
});
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.