jQuery
bind, live, delegate, on
名称 | 用法 | 例子 | 备注 |
---|---|---|---|
bind | $(selector).bind(event, data, function) | $(selector).bind("click", data, function); $(selector).bind("click dbclick mouseout", data, function); $(selector).bind({event1:function, event2:function, ...}) | jQuery 所有版本, 1.7后建议使用on |
live | $(selector).live(event, data, function) | $(selector).lve("click", data, function); $(selector).live({event1:function, event2:function, ...}) | 1.9以下版本, 1.9以上版本删除了此方法, 建议on方法代替 |
delegate | $(selector).delegate(childSelector, event, data, function); | $(selector).delegate(childselector, "click dbclick mouseout", data, function); $(selector).delegate(childselector, {event1:function, event2:function, ...}) | 1.4.2+ |
on | $(selector).on(event, childselector, data, function) | $(selector).on("click dbclick mouseout", childselector, data, function); $(selector).on({event1: function1, event2: function, ...}, childselector); | 1.7+, 用于替代bind, live |
相同点
- 都支持单元素多事件的绑定; 空格相隔方式或大括号替代方式;
- 均是通过事件冒泡方式, 将事件传递到document进行事件的响应;
不同点
- bind函数只能针对已经存在的元素进行事件的设置, 但是live, on, delegate均支持未来新添加元素事件的设置
- bind在jQuery1.7版本之前比较受推崇, 1.7版本以后, 官方已经不推荐使用, 替代函数为on
- live和delegate函数两者类似, 但live()函数在执行速度, 灵活性和CSS选择器支持方面较delegate差些
event.stopPropagation()
参考
- jQuery 主页 http://jquery.com/