Home >Web Front-end >JS Tutorial >Examples and precautions for using spaces in jQuery selectors_jquery

Examples and precautions for using spaces in jQuery selectors_jquery

WBOY
WBOYOriginal
2016-05-16 17:24:191076browse

This article is excerpted from "Sharp jQuery", with a little addition of my own.

The spaces in the selector cannot be ignored. One more space or one less space may lead to completely different results. Let’s look at an example.

First construct the following HTML code:

Copy the code The code is as follows:


Jquery tutorial

Jquery learning

Jquery plug-in

PHP learning



jQuery code:
Copy code The code is as follows:

var $test_a = $(".test :hidden");//jQuery with spaces Selector
var $test_b = $(".test:hidden");//jQuery selector without spaces
var len_a = $test_a.length;
var len_b = $test_b.length;
alert("The jQuery elements selected by the jQuery selector with spaces are: " len_a "");//The output is 4
alert("The jQuery elements selected by the jQuery selector without spaces Is: "len_b "pieces");//The output is 3

The reason why different results appear is that the descendant selector and the filter selector are different
Copy code The code is as follows:

var $test_a = $(".test :hidden");//with spaces The jQuery selector

The above code selects the hidden elements inside the element with class "test". (Descendant selector)
Copy code The code is as follows:

var $test_b = $(" .test:hidden");//jQuery selector without spaces

The above code selects the hidden element with class "test"

Note:
Some selectors must use spaces. If there are no spaces, the element cannot be obtained, for example:
Copy Code The code is as follows:

$("select:selected").length;//No matter at any time, this selector cannot get the element, this length It must be 0
$("select :selected");//This is correct

Some selectors must be used without spaces. If there are spaces, then The element cannot be obtained, for example:
Copy code The code is as follows:

$("input: checked").length;//No matter when, this selector cannot get an element, the length must be 0
$("input:checked");//This is correct
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn