随笔 - 394  文章 - 0  评论 - 946  阅读 - 143万 

.bind()方法

.bind()方法能够将一个操作绑定到特定的元素上去,然后在事件被调用的时候进行触发。需要注意的是.bind()方法只能够被绑定到已经存在的元素上去,才能够被执行。如果另一个符合要求的元素在.bind()事件绑定之后,才被添加到dom结构中,那么这个元素就不会被触发。

示例如下:

 

复制代码
jQuery:

$(
'.alertMe', '#bindExample').bind('click', function() {

alert(
'Clicked!');

});

$(
'#bindExample').append('<p class="alertMe">Alert <em>does not</em> fire on click!</p>');

HTML:

<div id="bindExample">

<!-- action is bound to this paragraph for the click event -->

<p class="alertMe">Alert fires on click!</p>

</div>
复制代码

 

但是,这个示例里面,新添加进去的元素是不能够被触发的。

 

.live()方法

和.bind()方法类似,.live()方法也能够将事件绑定到元素上面。然而,与之不同的是,.live()方法能够将与之匹配的元素进行事件绑定,即便是元素被动态的创建,并且在.live()方法调用之后被创建。

需要注意的是,dom遍历方法不完全支持传统的jQuery元素的搜索方法,比如,不支持

$('#foo').children('.bar').live('click',function(){//do something });

但是却支持:

$('#foo .bar').live('click', function() { /do something }); 

所以,最好的方法就是直接绑定元素,当然.find()方法也是可以被支持的。

示例如下:

jQuery:

$(
'.alertMe', '#liveExample').live('click', function() { alert('Clicked!');});$('#liveExample').append('<p class="alertMe">Alert fires on click (even though this was added after .live() was called)!</p>');HTML:

<!-- action is bound to this parent div for child paragraph's click event --><div id="liveExample"> <!-- action is not bound to this paragraph --> <p class="alertMe">Alert fires on click!</p></div>

这次,绑定事件就会被触发了。

 
.delegate()
方法

.delegate()
方法同
live
方法一样,也是绑定事件的,但是其效率要比
live
方法好上
4
倍不止,并且他只绑定选择器中指定的元素,而不是从根元素绑定开始。所以对于类似于
 
.delegate()不会被dom生成的元素所限制,但是.live()方法会。
示例如下:
jQuery:

$(
'#delegateExample').delegate('.alertMe', 'click', function() { alert('Clicked!');});$('#delegateExample').append('<p class="alertMe">Alert fires on click (even though this was added after .delegate() was called)!</p>');HTML:

<!-- action is bound to this parent div for child paragraph's click event --><div id="delegateExample"> <!-- action is not bound to this paragraph --> <p class="alertMe">Alert fires on click!</p></div>
posted on   程序诗人  阅读(1469)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示