以下代码之间有什么不同吗?
$('#whatever').on('click', function() {
/* your code here */
});
和
$('#whatever').click(function() {
/* your code here */
});
以下代码之间有什么不同吗?
$('#whatever').on('click', function() {
/* your code here */
});
和
$('#whatever').click(function() {
/* your code here */
});
我认为,区别在于使用模式.
我更喜欢.on
而不是.click
,因为前can使用更少的内存,并且用于动态添加的元素.
考虑下面的HTML:
<html>
<button id="add">Add new</button>
<div id="container">
<button class="alert">alert!</button>
</div>
</html>
我们通过以下方式添加新按钮
$("button#add").click(function() {
var html = "<button class='alert'>Alert!</button>";
$("button.alert:last").parent().append(html);
});
想要"alert !"显示alert .我们可以用"click"或"on"来表示这一点.
click
$("button.alert").click(function() {
alert(1);
});
通过以上步骤,将为every single element创建一个与 Select 器匹配的separate处理程序.这意味着
.on
$("div#container").on('click', 'button.alert', function() {
alert(1);
});
有了上面的内容,与您的 Select 器(包括动态创建的 Select 器)匹配的all elements的single处理程序.
.on
正如阿德里安在下面 comments 的那样,使用.on
的另一个原因是名称空间事件.
如果你添加一个.on("click", handler)
的处理器,你通常会用.off("click", handler)
删除它,这将删除这个处理器.显然,只有当你有一个函数的引用时,这才有效,所以如果你没有呢?您可以使用名称空间:
$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });
通过解除绑定
$("#element").off("click.someNamespace");