1. Trang chủ
  2. » Công Nghệ Thông Tin

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

10 333 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 886,2 KB

Nội dung

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 51 Figure 2-13. The spans are relocated to be next to one another so both can be wrapped .wrapInner() In some cases, it’s desirable to wrap the content of an element but not the tag itself. A good example of this is making an entire paragraph bold: to wrap strong tags around a paragraph is not valid HTML and, therefore, isn’t a desirable solution. Fortunately, jQuery provides .wrapInner(), which wraps everything contained within an element in a new tag. To italicize all text in the paragraphs on the test page, use the following code: $("p").wrapInner("<em />"); After execution, all the text on the page is italicized and the markup is validly nested (see Figure 2-14). CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 52 Figure 2-14. All text is italicized, and the em tags are inside the paragraph tags .remove() and .detach() To remove an element from the DOM entirely, the .remove() and .detach() methods are used. Both methods remove selected elements from the DOM, but the .detach() method keeps jQuery data for the element intact, which makes it ideal for situations in which an element will be reattached to the DOM at some point. Both .remove() and .detach() accept an optional selector to filter the elements being removed. In your example, remove all paragraphs with class foo using the following: $("p").remove(".foo"); When the code is run, the paragraph with class foo is removed from view and is no longer part of the DOM. To demonstrate the difference between .remove() and .detach(), you’ll have to jump ahead a bit and use a method called .data(), which allows developers to attach information to an element without adding additional tags or attributes .data() will be covered more thoroughly in the next section.) First, add some data to the first paragraph in the DOM. Then, with the data added, remove the element from the DOM using .detach(), reattach it, and attempt to read the data: $("p:first").data("test","This is some data."); var p = $("p:first").detach(); console.log("Data stored: "+p.data("test")); CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 53 ■ Note You're using a Firebug-specific object, console, and its .log() method to output specific information to the Firebug console. This is especially useful for debugging, but it needs to be removed before a project goes live to avoid JavaScript errors on computers that don't have Firebug installed. After running this code, the .data() method attaches some information to the first paragraph and gets removed from the DOM and stored in a variable; then the script attempts to output the value of the information stored with .data(). The console will output the following: >>> $("p:first").data("test","This is some ored: "+p.data("test")); Data stored: This is some data. Now, run the same test, but use .remove() instead of .detach(): $("p:first").data("test","This is some data."); var p = $("p:first").remove(); console.log("Data stored: "+p.data("test")); The output shows that the data was lost when the element was removed: >>> $("p:first").data("test","This is some ored: "+p.data("test")); Data stored: undefined Accessing and Modifying CSS and Attributes Previously, when you were creating DOM elements, you were able to define attributes such as CSS styles, the text contained within, and more. To access and modify this information for existing elements, jQuery has a set of built-in methods. .attr() For most element attributes, the .attr() method is used. This method has two purposes: The first is to read a given attribute, which is accomplished by supplying the name of the desired attribute as the first argument to the method with no other arguments. The second is to set an attribute by passing the name of the attribute to be set as the first argument and the value to which it is to be set as the second. First, retrieve the ID of the last paragraph using the following: $("p:eq(3)").attr("id"); In the console, this produces the following output: CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 54 >>> $("p:eq(3)").attr("id"); "bar" Next, change the ID attribute of the last paragraph to "bat" using this code: $("#bar").attr("id", "bat"); After execution, the following displays in the console: >>> $("#bar").attr("id", "bat"); [ p#bat ] Now, if you try to select elements with an ID of bar, an empty result set is returned: >>> $("#bar"); [ ] However, you can now select a paragraph element with an ID of bat: >>> $("#bat"); [ p#bat ] Additionally, multiple attributes can be set using JSON format: $("p:eq(3)").attr({ "id":"baz", "title":"A captivating paragraph, isn't it?" }); After executing this code, the HTML panel of Firebug reveals that the paragraph’s markup has been changed: <p id="baz" title="A captivating paragraph, isn't it?"> .removeAttr() To remove an attribute, simply call .removeAttr() on the element from which you wish to remove the attribute and pass the attribute’s name. Enable the check box in the sample form by removing the disabled attribute: $(":checkbox").removeAttr("disabled"); After executing this code, the check box can now be checked and unchecked at will. CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 55 .css() The .css() method works just like .attr(), except it applies to styling rules. To return a value, pass the name of the value as the only argument to the method; to set a value, pass both an attribute name and a new value for it. Like .attr(), multiple values can be set using JSON format. To change all elements with class foo to have red text and a yellow background, use the following: $(".foo").css({ "color":"red", "background":"yellow" }); This code, once executed, adds new style rules to the selected elements (see Figure 2-15). Figure 2-15. The document after adding CSS styling to elements with class foo Before reloading the page, retrieve the background value from elements with class foo using the following code: $(".foo").css("background"); This will return the following: >>> $(".foo").css("background"); "yellow none repeat scroll 0% 0%" CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 56 ■ Tip The values returned are CSS shorthand properties. 3 An added bonus of jQuery is the ability to set CSS properties using CSS shorthand, which doesn't work using basic JavaScript. .text() and .html() When dealing with the contents of an element, the .text() and .html() methods are used. The difference between the two is that .html() will allow you to read out and insert new HTML tags into an element, where .text() is for reading and writing text only. If either of these methods is called on an element set with no arguments, the contents of the element are returned. When a value is passed to the method, the existing value is overwritten, and the new one put in its place. To read the text out of the paragraph with ID bar, run the following code in the console: $("#bar").text(); This captures all text (including whitespace) but ignores the span tag. The following is output: >>> $("#bar").text(); "Paragraph with an id. And this sentence is in a span. " To read everything out of the paragraph, including the span tag, use the following code: $("#bar").html(); This results in the following: >>> $("#bar").html(); "Paragraph with an id. <span class="foo">And this sentence is in a span.</span> " Now, change the text by passing a value to the .text() method: 3 http://www.456bereastreet.com/archive/200502/efficient_css_with_shorthand_properties/ CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 57 $("#bar").text("This is new text."); The previous content of the paragraph is removed, and the new text is inserted. Note that the span tag was removed as well; all contents of an element are replaced when using .text() and .html(). To insert HTML into the paragraph, replace its contents again with the following snippet: $("#bar").html("This is some <strong>HTML</strong> text."); After execution, the new text appears in the paragraph and the word “HTML” appears in bold (see Figure 2-16). Figure 2-16. The browser after inserting text and HTML tags .val() Accessing and modifying the content of form elements is accomplished through the .val() method. This method returns the value of an input, or if a value is supplied, sets the value of an input. Retrieve the value of the submit button in your test form using the following: $(":submit").val(); which outputs this: >>> $(":submit").val(); "Log In" Now, update the value of the submit input to read "Sign In" using this code: CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 58 $(":submit").val("Sign In"); The submit button is called Sign In after running the preceding code snippet. .data() Previously, you used the .data() method to store information for a test of .remove() and .detach(). The .data() method does exactly that: it allows you to store information about an element within the jQuery object in a safe, easy manner. To give the first two paragraphs in the test document nicknames, store the information using .data() and then log it in the console: $("p:first") .data("nickname", "Pookie") .next("p") .data("nickname", "Shnookums"); console.log("My nickname: "+$("p:first").data("nickname")); console.log("My nickname: "+$("p:eq(1)").data("nickname")); After executing this script, the following will be logged in the console: >>> $("p:first") .data("nick name: "+$("p:eq(1)").data("nickname")); My nickname: Pookie My nickname: Shnookums Data can be added to an element en masse as in JSON format as well: $("p.foo").data({ "nickname":"Wubby", "favorite":{ "movie":"Pretty Woman", "music":"Sade", "color":"pink" } }); console.log("Nickname: "+$("p.foo").data("nickname")); console.log("Favorite Movie: "+$("p.foo").data("favorite").movie); The preceding will produce the following output when executed: CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 59 >>> $("p.foo").data({ "nickname":"Wubby", data("favorite").movie); Nickname: Wubby Favorite Movie: Pretty Woman This can also be simplified by caching the data in a variable, like so: $("p.foo").data({ "nickname":"Wubby", "favorite":{ "movie":"Pretty Woman", "music":"Sade", "color":"pink" } }); var info = $("p.foo").data(); // cache the data object in a variable console.log("Nickname: "+info.nickname); console.log("Favorite Movie: "+info.favorite.movie); This produces an identical result to the previous example, but performs a little better and is a bit easier to read. .addClass(), .removeClass(), and .toggleClass() A trio of shortcut methods was written for dealing with classes, since their use is so integral to modern web design. The first two methods, .addClass() and .removeClass(), simply add or remove a class attribute, respectively: $("p:first").addClass("bat"); console.log("Text: "+$(".bat").text()); $("p:first").removeClass("bat"); console.log("Text: "+$(".bat").text()); The preceding snippet outputs the following in the console: >>> $("p:first").addClass("bat" le.log("Text: "+$(".bat").text()); Text: Hello World! Text: The third method, .toggleClass(), accepts a class name or names and then either adds the class if it doesn’t already exist for the element or removes it if the class already exists. CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 60 Add the class baz and remove the class foo from the second paragraph in the example page using the following code: $("p.foo").toggleClass("foo baz"); Upon execution, the paragraph is modified and appears with the old class removed and the new one added (see Figure 2-17). Figure 2-17. The foo class is removed, and the baz class is added. To revert to the original class of foo and remove baz, select the paragraph, and apply .toggleClass() again: $("p.baz").toggleClass("foo baz"); This results in the paragraph going back to having only one class: foo. .hasClass() The .hasClass() method works similarly to the .is() method in that it determines if a class exists on a selected element and then returns either true or false. This makes it ideal for callback functions. Check if the first paragraph has class foo, and conditionally output a message using the following: var msg = $("p:eq(1)").hasClass("foo") ? "Found!" : "Nope!"; console.log("Class? "+msg); . the new text appears in the paragraph and the word “HTML” appears in bold (see Figure 2-1 6) . Figure 2-1 6. The browser after inserting text and HTML tags .val() Accessing and modifying the. This code, once executed, adds new style rules to the selected elements (see Figure 2-1 5). Figure 2-1 5. The document after adding CSS styling to elements with class foo Before reloading the. repeat scroll 0% 0%" CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS 56 ■ Tip The values returned are CSS shorthand properties. 3 An added bonus of jQuery is the ability to set CSS properties

Ngày đăng: 04/07/2014, 17:20

TỪ KHÓA LIÊN QUAN