最合适的方法:$($(" .answer")[0]) [英] Most appropriate way to get this: $($(".answer")[0])

查看:52
本文介绍了最合适的方法:$($(" .answer")[0])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想获得该类所有元素中的第一个元素.answer

Suppose I want to get the first element amongst all the elements of the class ".answer"

$($(".answer")[0])

我可以做到以上,但最佳平衡是什么优雅和速度之间?

I can do the above, but what is the best balance between elegance and speed?

*改变了问题以反映当前的讨论

*changed the question to reflect the current discussion

推荐答案

以下都是功能相同的(虽然不是速度):

The following are all equivalent in functionality (though not speed):

  • var a0 = $($('.answer')[0]);
  • var a0 = $('.answer').first(); - see http://api.jquery.com/first/
  • var a0 = $('.answer:first'); - see http://api.jquery.com/first-selector/
  • var a0 = $('.answer').eq(0); - see http://api.jquery.com/eq/
  • var a0 = $('.answer:eq(0)'); - see http://api.jquery.com/eq-selector/

哪个最好?

已假设选择器版本应该比方法版本更快(并且逻辑有一定意义)但我还没有找到可靠的跨浏览器,多文档基准测试,证明这是真的。

Which is the best?
It has been hypothesized that the selector versions should be faster than the method versions (and the logic makes some sense) but I have not yet found a reliable cross-browser, multi-document benchmark that proves this to be true.

在某些情况下,你不能使用选择器,因为你有一个由链式结果产生的jQuery对象,后来必须将其削减。

编辑:根据以下@ yc测试的优秀信息,以下是当前(2011年2月4日)的测试结果,总结并与基准<$ c $进行比较c> .answer:first :

Edit: Based on the excellent information from @yc's tests below, following are the current (2011-Feb-4) test results summarized and compared against a baseline of .answer:first:


          :first  :eq(0)  .first()  .eq(0)  $($('...')[0])
Chrome 8+   100%     92%      224%    266%       367%
   FF 3.6   100%    100%      277%    270%       309%
  FF 4.0b   100%    103%      537%    521%       643%
 Safari 5   100%     93%      349%    352%       467%
 Opera 11   100%    103%      373%    374%       465%
     IE 8   100%    101%     1130%   1246%      1767%
 iPhone 4   100%     95%      269%    316%       403%
=====================================================
 Weighted   100%     92%      286%    295%       405%
    Major   100%     95%      258%    280%       366%




  • 加权行显示按每个浏览器的测试次数加权的性能;流行的浏览器(在这些测试中)计算得更强。

  • 主要行显示相同,仅包括主要桌面浏览器的非beta版本。

    • The Weighted line shows the performance weighted by the number of tests per browser; popular browsers (among those testing) are counted more strongly.
    • The Major line shows the same, only including non-beta releases of the major desktop browsers.
    • 总结:假设(目前)是错误的。这些方法明显快于Sizzle选择器,并且几乎没有例外,OP的代码 $($('。answer')[0])是最快的!

      In summary: the hypothesis is (currently) wrong. The methods are significantly faster than the Sizzle selectors, and with almost no exception the OP's code $($('.answer')[0]) is the fastest of them all!

      这篇关于最合适的方法:$($(&quot; .answer&quot;)[0])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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