在 jQuery 选择器中使用前导冒号的目的是什么?

我已经开始使用 Wijmo 工具箱,并且在他们的文档页面中遇到了很多类似的示例选择器:

$(":input[type='radio']").wijradio();

我会这样写:

$('input[type=radio]').wijradio();

这些也一样吗,还是我遗漏了什么?

请注意,上面有两个不同之处: 第一个选择器前面带有冒号,并且输入类型带有引号。

29429 次浏览

The :input selector basically selects all form controls(input, textarea, select and button elements) where as input selector selects all the elements by tag name input.

Since radio button is a form element and also it uses input tag so they both can be used to select radio button. However both approaches differ the way they find the elements and thus each have different performance benefits.

:input is a jQuery extension while input is a CSS selector.

textarea, button, and select elements would be matched by the former, but not the latter.

The latter is faster, so use it for your specific radio example. Use :input when you want "all form elements" even if they aren't strictly <input> tags. Even in that case, the recommendation is to use a standard CSS selector first, then use .filter(':input') on that set.

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

In the 1.7.2 source, the :input filter tests a regular expression against the nodeName:

input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},

the $("input") selector will choose only elements of the type input

while the $(":input") selector will catch all the inputs elements (such as textarea, select, input etc...)

for further information, go the jQuery official documentation about the :input selector at:

http://api.jquery.com/input-selector/