.eq()、.get()和:nth-child()之间的区别是什么?

3
我最近一直在优化我的编码,使其更整洁、清晰和紧凑。但是我遇到了一个小问题。
我不确定何时应该使用像.eq()这样的函数而不是.get():nth-child()等函数。比如说,使用其中一个函数会有什么好处?对于重复事件、多个函数或仅单个使用的函数,哪种函数更适合呢?我可以阅读关于它们在某些情况下的用法,但只是了解表面,有时甚至会出现一个人使用一种方法,另一种来源则使用另一种方法,但实际上都是做同样的事情。
这是我需要澄清的“灰色”地带,请给予我帮助。
1个回答

7
  • .eq(n) retrieves the n-1th jQuery object.
  • .get(n) retrieves the n-1th DOM element. It'd be like doing .eq(n)[0].
  • :nth-child() is for more complex selectors like :nth-child(2n+1).

    You could use it in place of :eq() in selector strings, but I tend to stay away from it and use .eq() to make the selector more readable:

    $('ul.parent > li.child:nth-child(2)')
    $('ul.parent > li.child:eq(2)')
    $('ul.parent > li.child').eq(2)
    

哦,你比我快了 :( - gustavohenke
所以我基本上应该使用.eq()方法,因为它更加通用,可以在字符串等中使用。但是它能否被另一个函数调用以后呢? - Epik
1
@Epik:它们是不同的工具。这就像你在问要用锤子还是螺丝刀一样。如果你需要DOM对象,请使用.get()。如果你需要jQuery对象,请使用.eq() - Blender
好的,现在我明白了很多,谢谢你。我接受你的答案,因为它是正确的,并清楚地解释了这些差异。 - Epik
第一个例子应该是$('ul.parent > li.child:nth-child(3)'),因为nth-child选择器从1开始。 - Armando Contestabile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接