jQuery性能,.css或addClass [英] jQuery performance, .css or addClass

查看:157
本文介绍了jQuery性能,.css或addClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的jQuery代码,我在思考我的功能的速度性能。当一个元素被点击(mousedown),我需要分配一个图像作为背景。我可以通过两种方式:

  $('#element li.class')。css({background: someimageURL}); 

  $('#element li.class')。addClass(someclass); 

其中someclass有实际的CSS背景图片。



有没有办法测试各种功能的速度?



谢谢 $ .addClass()

$

$ p

解决方案>将是两者中较快的。这涉及到对元素的另一个类名的基本定位,而替代方法将需要遍历元素样式并设置许多明确的规则。



通过<$设置一对css规则c $ c> $。css()可能没有什么可担心的,但如果你发现自己设置了很多,通常是时候创建一个类,并根据需要应用/删除。 >

我已将两种方法的逻辑提取到一个位置,供您查看是否喜欢。



http://pastie.org/842738


I have a big jQuery code and I am thinking at speed performance of my functions. When an element is clicked (mousedown) i need to assign an image as background. I can do this by 2 ways:

$('#element li.class').css({"background":"someimageURL"});

or

$('#element li.class').addClass("someclass");

where "someclass" have the actual CSS background image. Witch function works better in this case.

Is there a way to test various functions speed?

Thank you

解决方案

I'm almost certain .addClass() would be the faster of the two. This involves essentially tacking on another classname to the element, whereas the alternative would require iterating through the elements styles and setting many explicit rules.

Setting a couple css rules via $.css() is likely nothing to worry about, but if you find yourself setting many, often, it's time to create a class and apply/remove that as needed.

I've extracted the logic of both methods into a single location for you to review if you like.

http://pastie.org/842738

这篇关于jQuery性能,.css或addClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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