Tải bản đầy đủ (.pdf) (10 trang)

Tương tác giữa PHP và jQuery - part 4 pps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (574.42 KB, 10 trang )

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

31
$("p.foo").next();
This generates the following output:
>>> $("p.foo").next();

[ p ]
A selector can be passed to .next() as well, which allows developers to determine which type of next
sibling element should be matched:
$("p.foo").next("#bar");
This returns an empty result set, since the next element does not have an ID of bar:
>>> $("p.foo").next("#bar");

[ ]
Because .next() returns only one element, a companion method was created that returns all next
sibling elements, .nextAll(). To select all paragraphs after the paragraph with the class foo, use the
following code:
$(".foo").nextAll("p");
This returns the following result:
>>> $(".foo").nextAll("p");

[ p, p#bar ]
■ Note The selector is optional in .nextAll(), as it is in .next().
The third method available for selecting next sibling elements is the .nextUntil() method. As its
name suggests, this method will return all next elements until a selector is matched. It’s important to
note that the element matched by the selector will not be included in the result set.
To demonstrate this, select the paragraph with the class foo and use .nextUntil() with a selector of
"#bar":
$(".foo").nextUntil("#bar");
Only one paragraph is returned in the result set, and the paragraph with the ID of bar is not


included:
>>> $(".foo").nextUntil("#bar");

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

32
[ p ]
To include the paragraph with an ID of bar, you need to look at the element immediately following,
which is the form element in this case. Try the selector again using this updated code:
$(".foo").nextUntil("form");
Now, both following paragraphs are returned:
>>> $(".foo").nextUntil("form");

[ p, p#bar ]
.prev(), .prevAll(), and .prevUntil()
The .prev(), .prevAll(), and .prevUntil() functions work exactly like .next(), .nextAll(), and
.nextUntil(), except they look at previous sibling elements rather than next sibling elements:
>>> $("#bar").prev();
[ p ]

>>> $("#bar").prevAll();
[ p, p.foo, p ]

>>> $("#bar").prevUntil(".foo");
[ p ]
.siblings()
To select sibling elements on both sides of an element, use the .siblings() method. This accepts a
selector as an argument to limit what types of elements are returned. To match all sibling paragraph
elements to the paragraph with ID bar, execute the following code:
$("#bar").siblings("p");

The results will look as follows:
>>> $("#bar").siblings("p");

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

33
[ p, p.foo, p ]
.parent()
The .parent() method returns a set of the immediate parent elements of the current selection. For
instance, to select all parent elements of any elements with the class foo, use the following:
$(".foo").parent();
This returns the following:
>>> $(".foo").parent();

[ body, p#bar ]
To match only paragraph elements that are parents of elements with class foo, modify the code to
the following:
$(".foo").parent("p");
This narrows the result set:
>>> $(".foo").parent("p");
[ p#bar ]
.parents() and .parentsUntil()
Unlike .parent(), .parents() will return all parent elements, with an optional selector passed to filter
the results.
To select all parent elements of the check box in the form on the example page, use the following
code:
$(":checkbox").parents();
This finds every parent element, all the way out to the html element:
>>> $(":checkbox").parents();


[ label, fieldset, form #, body, html ]
To filter the results so that only the parent form element is returned, modify the code as follows:
$(":checkbox").parents("form");
This returns only the parent form element:
>>> $(":checkbox").parents("form");
CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

34
[ form # ]
Finally, to select a range of parents until a selector is matched, similar to .nextUntil() or
.prevUntil(), use .parentsUntil():
$(":checkbox").parentsUntil("form");
This returns all parent elements until the form element is encountered:
>>> $(":checkbox").parentsUntil("form");

[ label, fieldset ]
.add()
The .add() method is versatile and, therefore, a bit more complicated. Essentially, it allows you to add
additional elements to the existing jQuery object using a selector or a string of HTML.
To select all paragraphs and then add the span with class foo to the object, use the following:
$("p").add("span.foo");
This outputs the following:
>>> $("p").add("span.foo");

[ p, p.foo, p, p#bar, span.foo ]
The .add() method also allows you to create elements on the fly, like so:
$("p").add('<span id="bat">This is a new span</span>');
Executing the preceding code will output this:
>>> $("p").add('<span id="bat">This is a new span</span>');


[ p, p.foo, p, p#bar, span#bat ]
■ Note Notice that the element span#bat is faded in the console output. This happens because, while the element
exists in the jQuery object, it has not been appended to the DOM and, therefore, does not display on the page.
You'll learn how to add new elements to the DOM in the next section, “Creating and Inserting DOM Elements.”
CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

35
.andSelf()
If you’re using a traversal method, you may want to keep the original matched set of elements as well.
The .andSelf() method provides this ability by allowing the original set to be recalled and appended to
the new set.
For instance, to match all paragraph elements and then find child spans, use the following code:
$("p").find("span");
This returns the spans in the document, but you’ve lost the paragraphs:
>>> $("p").find("span");
[ span, span.foo ]
To keep the paragraphs and match the spans, add a call to .andSelf() to the end of the code:
$("p").find("span").andSelf();
This results in the desired output:
>>> $("p").find("span").andSelf();

[ p, p.foo, p, span, p#bar, span.foo ]
.contents()
The .contents() method works similarly to the .children() method, except .contents() returns text
nodes as well, which are simply the character data contained within an element (the actual text displayed
by an element).
1

To find all contents of the span with class foo, use the following:
$("span.foo").contents();

This results in the following output:
>>> $("span.foo").contents();

[ <TextNode textContent="And this sentence is in a span."> ]


1

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

36
.end()
At times in jQuery scripts, you will find it necessary to back up to the last set of elements stored in the
jQuery object. The .end() method does exactly that: it reverts the jQuery object to the state immediately
preceding the last filtering action in the current jQuery object chain.
To select all paragraphs, then find all spans, the original set of paragraphs is no longer available:
>>> $("p").find("span");

[ span, span.foo ]

To revert back to the set of paragraphs, add .end() to the chain:

>>> $("p").find("span").end();

[ p, p.foo, p, p#bar ]
Creating and Inserting DOM Elements
The first thing you’ll learn that actually changes the DOM, rather than simply selecting elements from it,
is how to create new elements and insert them into the DOM. Since the release of jQuery 1.4, this is
pretty straightforward.
This section of the book starts using more involved code snippets, and will therefore require a minor

adjustment to your Firebug console. At the bottom right of the console, there is a round button with an
arrow pointing upward (see Figure 2-1).
CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

37

Figure 2-1. The button to activate the multiline console test area
Click this button to activate the multiline testing area, where you’ll be able to enter commands
across multiple lines, making them easier to read and allowing for more advanced examples (see
Figure 2-2).
CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

38

Figure 2-2. The multiline testing area (shown at the right-hand side of the console)
With the multiline testing area, you now need to click the Run button at the bottom to execute the
code. Pressing Enter, as with the single-line test console, will now break to a new line.
Creating New DOM Elements
To create a new DOM element, jQuery only needs the tag to be created. For instance, to create a new
paragraph element, you would use the following:
$("<p>");
To add attributes and text to this element, you can simply write it out as plain HTML:
$('<p class="bat">This is a new paragraph!</p>');
CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

39
■ Note The preceding example uses single quotation marks to enclose the string of HTML rather than double
ones. This has no effect on the jQuery function; it merely eliminates the need to escape the double quotes used in
the class attribute (e.g.,
class=\"bat\").

As of jQuery 1.4, you can also add attributes to this new element by passing a second argument as
JavaScript Object Notation (JSON)
2
:
$("<p>", {
"class":"bat",
"text":"This is a new paragraph!"
});
The result of the above code snippet is the following:
>>> $("<p>", { "class":"bat", "text":"This is a new paragraph!" });

[ p.bat ]
Because this is only creating the element, it hasn’t been attached to the DOM yet and, therefore,
isn’t visible in the browser window. You’ll learn to insert new elements in the next section, “Inserting
New Elements into the DOM.”
■ Note At its simplest, JSON is a key-value pairing where both the key and value are surrounded by quotation
marks and all key-value pairs are comma-separated and enclosed in curly braces ({}). A sample of JSON data
would be
{ "key":"value" } or { "key1":"value1", "key2":"value2" }.
Inserting New Elements into the DOM
Now that you have a basic understanding of how to create new elements, you can begin learning how to
insert them into the DOM. jQuery provides several methods for handling this, which you’ll explore in
this section.
An important note to make here is that the modification of the DOM is temporary, meaning that any
changes made will be reset back to the original HTML document once the page is refreshed. This
happens because JavaScript is a client-side language, which means it isn’t modifying the actual files from
the server, but the browser’s individual interpretation of the file.


2


CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS

40
Changes made with JavaScript can be saved on the server through the use of AJAX (which you’ll
learn about later in this chapter), which allows JavaScript to interface with server-side languages such as
PHP.
■ Note After performing the examples in each of the following sections, refresh your page so each new example
is starting with a fresh copy of the example HTML file.
.append() and .prepend()
The .append() and .prepend() functions will attach the elements passed as arguments to the jQuery
object to which they are chained. The only difference is that .append() attaches the elements at the end,
and .prepend() attaches at the beginning.
The content will be appended or prepended inside the matched elements, meaning if you match all
paragraphs on the page and append a new sentence, “This was added by jQuery”, it will be appended
inside the closing paragraph tag (</p>).
Try this out by entering the following code into your console:
$("p").append(" This was added by jQuery.");
Executing the code will add this sentence to the end of each paragraph inside the closing paragraph
tag. This is evident because the text is not knocked to the next line, as it would be if it were outside the
closing tag.























×