JQuery Event Handlers - Qual é o melhor método
Qual é a diferença entre as seguintes maneiras de anexar um manipulador de eventos no JQuer
(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";
});
})();
Encontrei alguns casos em que um parece funcionar e o outro não. Por exemploHandler 2 abaixo, faznã trabalhe enquantoHandler 1 faz. Para fazer esse trabalho, eu tive que implementarHandler 3 que é obviamente menos eficiente.
$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
});
Aqui está o 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>