What's the difference between the following ways of attaching an event handler in JQuery?
(function () {
var $body = $("body");
$('button').click(function () {
console.log(this) + " - 1";
});
$('button').on('click', function () {
console.log(this) + " - 2";
});
$(document).on('click', 'button', function () {
console.log(this) + " - 3";
});
$body.on('click', 'button', function () {
console.log(this) + " - 4";
});
$body.find('button').on('click', function () {
console.log(this) + " - 5";
});
})();
I have found some cases where one seems to work and the other does not. For example Handler 2 below, does not work while Handler 1 does. In order to make this work I had to implement Handler 3 which is obviously less efficient.
$retrieveCust = $("#bxRetrieveCustomer");
// Handler 1
$retrieveCust.find(".icoX").on("click", function () {
// DO SOMETHING
});
// Handler 2
$retrieveCust.find(".tag-open").on("click", function () {
// DO SOMETHING
});
// Handler 3
$(document).on("click", ".tag-open", function (event) {
// DO SOMETHING
});
Here's the HTML
<div class="box" id="bxRetrieveCustomer">
<h1>RETREIVE CUSTOMER</h1>
<div class="icoX">X</div>
<div class="box-liner10">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Email</th>
<th>password</th>
<th></th>
</tr>
<!-- ko foreach: Customers -->
<tr>
<td data-bind="text: FirstName"></td>
<td data-bind="text: LastName"></td>
<td data-bind="text: DateOfBirth"></td>
<td data-bind="text: Email"></td>
<td data-bind="text: Pwd"></td>
<td><a class="tag-open"></a></td>
</tr>
<!-- /ko -->
</table>
</div>
</div>