问题
I wonder why people seems to prefer :input
over input
as a jQuery selector? Basically, this two lines seem to do the same thing :
$('input:first').focus()
$(':input:first').focus()
But second version is more widely use, and I don't find why. Moreover, the :input
selector seem slower according to this benchmark: http://jsperf.com/input-vs-input/2
回答1:
:input
is pseudo selector by jQuery which includes <buttons>
, <textarea>
, e.t.c
input
is a tag match which strictly matches <input>
.
This additional note about :input
is informative:
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 DOMquerySelectorAll()
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")
.
--from https://api.jquery.com/input-selector/
回答2:
input
is just the input element selector. :input also selects textarea
, select
, and button
(form controls).
It's not necessarily a matter of preference since in actuality they do somewhat different things.
回答3:
:input selects all input, textarea, select and button elements, while input
just selects elements with an input tag.
来源:https://stackoverflow.com/questions/14863751/input-vs-input-in-jquery