添加.live以单击jquery中的函数 [英] adding .live to click functions in jquery
问题描述
我们有一个使用大量jquery的应用程序,我们将所有脚本添加到init.js文件中,该文件有很多 .live(click),. lt (悬停)
等,东西加上一些 if($(。classname)。length)
等。
We have an app that uses a lot of jquery stuff and we're adding up all our scripts in an init.js file which has a lot of .live("click"), .live("hover")
etc, stuff plus some if($(".classname").length)
etc.
我怀疑它可能会不必要地减慢我们的页面速度(有些页面不需要一些脚本)。但是对于这个更优雅的解决方案是什么?对于每个需要它的页面,我们当然不会喜欢单独的文件,这是一个很难维护的问题。还有其他方法可以实现吗?
I have a suspicion it MIGHT be slowing down our pages unnecessarily(some pages don't need some scripts). But what is a more elegant solution to this? We certainly won't like a separate file for each page that needs it, that's a pain to maintain. Is there any other way to achieve this?
推荐答案
在函数中包装特定于页面的内容并在每个页面上调用相应的函数。
Wrap your page-specific things in functions and call the appropriate function on every page.
另一个解决方案是将URL映射到函数并自动调用适用于当前URL的函数 - 然后你就不需要在页面上使用任何JS。
Another solution would be mapping URLs to functions and calling the functions applicable for the current URL automatically - then you would not need any JS on the pages itself.
对于您的直播活动,您可以使用正文上的代表并为正文提供特定于页面的类: $('body.page-xyz')。 delegate('your-live-selector','click',function(){...})
For your live events you could use delegates on the body and give the body a page-specific class: $('body.page-xyz').delegate('your-live-selector', 'click', function(){...})
这只会附加一个事件处理程序,如果正文具有正确的类。
This only attaches an event handler if the body has the correct class.
这篇关于添加.live以单击jquery中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!