javascript - on(), live(), bind() 之间有什么区别呢
PHPz
PHPz 2017-04-10 12:44:29
[JavaScript讨论组]

jQuery中看着实现的效果都是一样的,不知道有什么具体区别呢?

PHPz
PHPz

学习是最好的投资!

全部回复(3)
天蓬老师

bind是直接绑定在一个对象上。

$('#foo').bind('click', function() {
    alert('User clicked on "foo."');
});

这个例子的是绑定在 #foo 这个元素上。点击#foo元素后执行回调函数。

on方法是一个事件委托。

$('#foo').on("click", "a", function(){ 
    alert("Goodbye!");
});

这个例子是委托在 #foo 这个元素上,点击 #foo 的子元素 a 标签才执行回调函数。

live 方法是on方法的一种实现。

$('a').live('click', function(){ 
    alert("Goodbye!");
});
$(document).on("click", "a", function(){ 
    alert("Goodbye!");
});

上面这两个方法完全相同,后者是前者的具体实现。

PHP中文网

http://api.jquery.com/live/
Attach an event handler for all elements which match the current selector, now and in the future. (动态生成的也行)

--------------------------------------
http://api.jquery.com/bind/
Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. (先决条件,绑定的dom element必须已经存在)
------------------

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

手册上有相关用法例子

$("a.offsite").live("click", function(){ alert("Goodbye!"); });               
$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });
$('#foo').bind('click', function() {alert('User clicked on "foo."');});

on的这个$(document), 请参考 http://stackoverflow.com/questions/81...

迷茫

不要管他们的区别。用1.9版本JQ,只有on

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号