.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>
分类:
.NET 杂谈记录
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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 让容器管理更轻松!