Reputation: 14313
I was playing around with the concept of using arrow functions to execute small parts of code and then I started getting functionality that perplexed me.
When you compare the following with it's functional counterpart (listed bellow):
$("#test").click((e) => $(e.target).remove());
$("#subtest").click((e) => true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test
<div id="subtest">test2</div>
</div>
$("#test").click(function (e) {
$(this).remove()
});
$("#subtest").click(function () {
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test
<div id="subtest">test2</div>
</div>
I am certain this has something to do with what e.target
is referencing because if I use e.currentTarget
is seems to work.
$("#test").click((e) => $(e.currentTarget).remove());
$("#subtest").click((e) => true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test
<div id="subtest">test2</div>
</div>
I haven't gotten a real satisfying answer via Google for this functionality, some help would be much appreciated.
Upvotes: 0
Views: 46
Reputation: 171669
target
will not be the element of the selector if there are child elements and those children are acted upon
In your case you have a child that would actually be the target. This is easy to verify by console.log(e.target)
Conversely currentTarget
will be the same as the selector element and is not necessarily the same as target
. In a non arrow function handler, currentTarget
is same as this
Upvotes: 2