jQuery 提供了多种绑定事件的方式, 每种方式各有其特点, 明白了它们之间的异同点, 有助于我们在写代码的时候进行正确的选择, 从而写出优雅而容易维护的代码. 下面我们来看下 jQuery 中绑定事件的方式都有哪些, 希望对大家有所帮助.
jQuery 中事件绑定的方法有: bind(),live(),delegate(),on(), 对应的解除监听的函数分别是 unbind,die,undelegate,off.
1,bind:bind(type [,data], fn)
bind 是使用频率较高的一种, 作用就是在选择到的元素上绑定特定事件类型的监听函数.
bind, 监听器绑定到目标元素上, 会将所有匹配的元素都绑定一次事件. 因此, 当元素很多时, 后来动态添加的元素不会被绑定.
例:
- $("#foo").bind('click',function(){
- console.log("clicked");
- })
简写:
- $("#foo").click(function(){
- console.log("clicked");
- })
- 2,live
live, 监听器绑定到 document 上, 利用事件委托, 可以像调用 bind 一样调用 live 方法, 但两者的底层实现不一样..live 绑定的事件也会匹配到那些动态添加的元素, 而且, 被 live 绑定的事件只会被附加到 document 元素上一次, 因此提高了性能.
例:
$( "#members li a" ).live( "click", function( e ) {} );
注意: 该方法在 1.7 版本后被弃用
3,delegate:$(selector).delegate(childSelector,event,data,function)
.delegate 与. live 类似, 不会监听器绑定到你指定的附加元素上, 而不是 document 上, 也利用了事件委托, 因此也提高了性能. 但是该方法不能直接由 bind 过渡
例:
- $( "#members" ).delegate( "li a", "click", function( e ) {
- } );
- 4,on:$(selector).on(event,childSelector,data,function)
1.7 版本新添加的, 也是推荐使用的事件绑定方法. 其实 bind,live,delegate 都是通过该方法实现的:
- bind: function( types, data, fn ) {
- return this.on( types, null, data, fn );
- },
- unbind: function( types, fn ) {
- return this.off( types, null, fn );
- },
- live: function( types, data, fn ) {
- jQuery( this.context ).on( types, this.selector, data, fn );
- return this;
- },
- die: function( types, fn ) {
- jQuery( this.context ).off( types, this.selector || "**", fn );
- return this;
- },
- delegate: function( selector, types, data, fn ) {
- return this.on( types, selector, data, fn );
- },
- undelegate: function( selector, types, fn ) {
- return arguments.length == 1 ?
- this.off( selector, "**" ) :
- this.off( types, selector, fn );
因此, 使用 on 方法和使用以上个方法的一样
- // Bind
- $( "#members li a" ).on( "click", function( e ) {
- } );
- $( "#members li a" ).bind( "click", function( e ) {
- } );
- // Live
- $( document ).on( "click", "#members li a", function( e ) {
- } );
- $( "#members li a" ).live( "click", function( e ) {
- } );
- // Delegate
- $( "#members" ).on( "click", "li a", function( e ) {
- } );
- $( "#members" ).delegate( "li a", "click", function( e ) {
- } );
对于只需要触发一次, 随后就要立即解除绑定的情况, 也可以使用 one() 方法. 即在每个对象上, 事件处理函数只会被执行一次.
更多 web 前端 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/jquery/18224.html