jquery – .delegate()vs .on()

前端之家收集整理的这篇文章主要介绍了jquery – .delegate()vs .on()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的web应用程序中使用jQuery。我一直在使用.bind(),但我看到它有点慢,所以在阅读文档我阅读关于.on()和.delegate()。我理解如何.delegate()工作,但我不清楚什么是它和.on()之间的区别是什么是更好的在哪些情况下。

还有我使用jQuery 1.6所以我想知道如果它是值得的,准备我的脚本jQuery 1.7通过放入一个条件类似于以下:

if(typeof $(selector).on == 'function'){
    /* use .on() */
}else{
    /* use .delegate() */
}

这是一个好主意(为.on()准备)还是只是寻找麻烦什么?

请帮助我清楚地了解这些方法

解决方法

.on()语法是1.7版本使用的新语法,它用于替换.bind(),.delegate()和.live()。

更多在这里 – > http://blog.jquery.com/2011/11/03/jquery-1-7-released/

New Event APIs: .on() and .off()

The new .on() and .off() APIs unify all the ways of attaching events
to a document in jQuery — and they’re shorter to type!

$(elements).on( events [,selector] [,data],handler );
  $(elements).off( [ events ] [,handler] );

When a selector is provided,.on() is similar to .delegate() in that
it attaches a delegated event handler,filtered by the selector. When
the selector is omitted or null the call is like .bind(). There is one
ambiguous case: If the data argument is a string,you must provide
either a selector string or null so that the data isn’t mistaken as a
selector. Pass an object for data and you’ll never have to worry about
special cases.

All the existing event binding methods (and their corresponding unbinding methods) are still there in 1.7,but we recommend that you use .on() for any new jQuery project where you know version 1.7 or higher is in use. (emphasis mine)

原文链接:https://www.f2er.com/jquery/185149.html

猜你在找的jQuery相关文章