jQuery syntax
With jQuery, you can select (query) HTML elements and perform "actions" on them.
jQuery syntax
jQuery syntax is about selecting HTML elements and performing certain operations on the selected elements.
Basic syntax: $(selector).action()
- The dollar sign defines jQuery
- The selector "queries" and "finds" HTML elements
- jQuery's action() performs operations on the elements
Example:
-
$(this).hide() - hide the current element
-
$("p").hide() - hide all
Element
-
$("p.test").hide() - hide all with class="test"
Element
-
$("#test").hide() - hide the element with id="test"
|
| Are you familiar with CSS selectors?
jQuery 使用的语法是 XPath 与 CSS 选择器语法的组合。在本教程接下来的章节,您将学习到更多有关选择器的语法。 |
| --- | --- |
Document Ready Event
You may have noticed that all jQuery functions in our examples are placed inside a document ready function:
$
(
document
)
.
ready
(
function
(
)
{
//
Start writing jQuery code...
}
)
;
This is to prevent jQuery code from running before the document is fully loaded (ready), that is, the DOM can only be manipulated after it has finished loading.
If a function runs before the document is fully loaded, the operation may fail. Here are two specific examples:
- Trying to hide an element that does not exist
- Getting the size of an image that has not fully loaded
**Tip:** Shorthand (same effect as the above):
$
(
function
(
)
{
//
Start writing jQuery code...
}
)
;
You can choose whichever of the above two ways you prefer to execute jQuery methods after the document is ready.