.delegate()与.on() [英] .delegate() vs .on()

查看:88
本文介绍了.delegate()与.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/

新事件API:.on()和.off()

新的.on()和.off()API统一了所有附加事件的方式 到jQuery中的文档-键入起来就更短了!

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

提供选择器时,.on()与.delegate()相似,因为 它附加一个委托事件处理程序,该事件处理程序由选择器过滤.什么时候 选择器被省略或为null,调用类似于.bind().有一个 模棱两可的情况:如果data参数是字符串,则必须提供 选择器字符串或null,以使数据不会被误认为是 选择器.传递对象以获取数据,您无需担心 特殊情况.

所有现有的事件绑定方法(及其对应的 解除绑定方法)在1.7中仍然存在,但我们建议您 将.on()用于您知道版本1.7或以下版本的任何新jQuery项目 (强调我的意思)

I'm using jQuery in my web application. I've been using .bind() but I see that it is a little slow, so while reading the documentation I read about .on() and .delegate(). I understand how .delegate() works but I’m not clear on what is the difference between it and .on() or which is better in which scenarios.

Also I'm using jQuery 1.6 so I would like to know if it is worth it to prepare my script for jQuery 1.7 by putting in a condition similar to the following:

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

Is this a good idea (to prepare for .on()) or is it just looking for trouble for nothing?

Please help me to get clear understanding of these methods.

解决方案

The .on() syntax is the new syntax that version 1.7 uses and it is meant to substitute .bind(), .delegate() and .live().

More here -> 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 ] [, selector] [, 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)

这篇关于.delegate()与.on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆