Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass 'this' element via jquery on.('click') to the inside function

If I had an element such as

<div class='some_class' onclick='executeF(this)'/>

would this be equivalent to:

$('.some_class').on('click',function(e){
    executeF(this);
});

or

$('.some_class').on('click',function(e){
    executeF(e);
});

or

$('.some_class').on('click',function(e){
    executeF($(this));
});

I don't have the means to test this at the moment so I just wanted to make sure what would be the direct correspondent jquery method before going further on my coding since (again) I can't test this right now

like image 460
Fane Avatar asked Feb 08 '23 07:02

Fane


1 Answers

$('.some_class').on('click',function(e){
    executeF(e);
});

In above code, e stands for event object. To get current DOM element, you will need to use e.currentTarget

This here will represent the DOM element which has triggered event.

$(this) will give you jQuery's element array. can

You can test this on following code:

function Click(el) {
  console.log(el)
}

$(".some_class").on("click", function(e) {
  console.log("Event: ", e);
  console.log("Current Target of Event: ", e.currentTarget);
  console.log("this: ", this);
  console.log("$(this): ", $(this));
})
div {
  height: 100px;
  width: 100px;
  border: 1px solid silver;
  margin: 10px;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div onclick="Click(this)">JS</div>
<div class="some_class">JQuery</div>

Hope this helps!

like image 105
Rajesh Avatar answered Feb 11 '23 01:02

Rajesh