在jQuery中使用BIND或ON函数的最佳做法 [英] Best practice using BIND or ON functions in jQuery
问题描述
bind
将事件绑定到DOM。 我想知道他们之间是否有区别,在函数上使用的好处是什么?这将是一个很好的调用,将我的代码中的所有我的
的函数 p> bind
更改为
jQuery项目正在逐渐将越来越多的功能放在更少的方法中,而不是为每个单独的东西分别使用方法。 p>
方法 bind
, live
和委托
全部被中的单一方法取代,您可以使用不同类型的参数来确定该方法的作用。
比较:
$(sel).bind(event,f); = $(sel).on(event,f);
$(sel).live(event,f); = $(document.body).on(event,sel,f);
$(sel).delegate(sel2,event,f)= $(sel).on(event,sel2,f);
如果您使用 live
替换为,因为该方法的用法有点尴尬。此外, live
方法在body元素上创建一个委托,您应该尝试将代理绑定到更近的范围。
如果您使用 bind
和委托
,则不要将其替换为在
上。您可以在新的代码以及您编辑的代码中执行此操作,但这些方法在最近的将来不会消失。
Recently the jQuery team start recommending to use on
instead of bind
for binding events to the DOM.
I would like to know if there is a difference between them, what is the benefit of using the on
function and if it would be a good call of changing all my bind
's to on
's functions in my code?
The jQuery project is moving towards putting more and more functionality in fewer methods, instead of having separate methods for every separate thing.
The methods bind
, live
and delegate
have all been replaced by the single method on
, where you use parameters of different types to determine what the method does.
Comparison:
$(sel).bind(event, f); = $(sel).on(event, f);
$(sel).live(event, f); = $(document.body).on(event, sel, f);
$(sel).delegate(sel2, event, f) = $(sel).on(event, sel2, f);
If you are using live
, you should replace that, as the usage of that method is a bit awkward. Also, the live
method creates a delegate on the body element, and you should try to bind the delegate to a closer scope.
If you are using bind
and delegate
it's no panic to replace them with on
right away. You can do that in new code, and in code that you edit anyway, but those methods are not about to go away in the nearest future.
这篇关于在jQuery中使用BIND或ON函数的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!