【发布时间】:2012-03-16 00:38:09
【问题描述】:
在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";
});
})();
我发现了一些情况,其中一种似乎有效而另一种无效。例如下面的 Handler 2,不 工作,而 Handler 1 工作。为了完成这项工作,我必须实现明显效率较低的 Handler 3。
$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
});
这是 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>
【问题讨论】:
标签: jquery