当前位置: 代码迷 >> Web前端 >> (三)选择元素――(8)定制选择器(Custom selectors)
  详细解决方案

(三)选择元素――(8)定制选择器(Custom selectors)

热度:478   发布时间:2013-09-28 10:01:20.0
(3)选择元素――(8)定制选择器(Custom selectors)
To the wide variety of CSS selectors, jQuery adds its own custom selectors. These custom selectors enhance the already impressive capabilities of CSS selectors to locate page elements in new ways.

在多种多样的css选择器之上,jquery添加了他自己独特的选择器。这些选择器在新的方面扩展了已经令人印象深刻的css选择器去定位页面中元素的能力。

Performance note
When possible, jQuery uses the native DOM selector engine of the browser to find elements. This extremely fast approach is not possible when custom jQuery selectors are used. For this reason, it is recommended to avoid frequent use of custom selectors when a native option is available and performance is very important.

性能提示
jquery会尽可能的使用浏览器原生的DOM选择器引擎去查找元素。但是当定制选择器使用的时候,这个相当快速的方法通常是不能使用的。由于这个原因,当一个原生选项可用的时候,我们推荐避免经常使用定制选择器,性能是很重要的。

Most of the custom selectors allow us to pick certain elements out of a line-up, so to speak. Typically used following a CSS selector, this kind of custom selector identifies elements based on their positions within the previously-selected group. The syntax is the same as the CSS pseudo-classsyntax, where the selector starts with a colon (:). For example, to select the second item from a set of <div>elements with a class of horizontal, we write the following code:

$('div.horizontal:eq(1)')

说起来,大部分定制选择器允许我们从一排元素中找到特定的元素,这种选择器依靠他们在之前选择的一组元素的位置确定元素,典型的在下面的css选择器中使用了。这个语法和css伪类语法一致,这个选择器以冒号开头,例如,为了选择一系列有着horizontal类的div元素中的第二个,我们写下了下面的代码:$('div.horizontal:eq(1)')

Note that :eq(1)selects the second item in the set because JavaScript array numbering is zero-based, meaning that it starts with 0. In contrast, CSS is one-based, so a CSS selector such as $('div:nth-child(1)')would select all divselectors that are the first child of their parent (in this case, however, we would probably use 

$('div:first-child')instead).

注意:eq(1)选择了这组元素中的第二个,因为js数组是zero-base的,意味者js数组从0开始计数的,作为对比,css是one-base,因此一个如同$('div:nth-child(1)')的css选择器将选择他们父元素的第一个子元素(在这个场景下,我们当然还可以使用$('div:first-child'))。

  相关解决方案