Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 23 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
23
Dung lượng
1,12 MB
Nội dung
28 CHAPTER 2 Creating the wrapped element set input:checked narrows the search to only <input> elements that are checked. The custom :checked selector works like a CSS attribute selector (such as [foo=bar] ) in that both filter the matching set of elements by some criteria. Com- bining these custom selectors can be powerful; consider :radio:checked and :checkbox:checked . As we discussed earlier, jQuery supports all of the CSS filter selectors and also a number of custom selectors defined by jQuery. They are described in table 2.3. Table 2.3 The jQuery custom filter selectors that give immense power to identify target elements Selector Description :animated Selects elements that are currently under animated control. Chapter 5 will cover animations and effects. :button Selects any button (input[type=submit], input[type=reset], input[type=button], or button). :checkbox Selects only check box elements (input[type=checkbox]). :checked Selects only check boxes or radio buttons that are checked (supported by CSS). :contains(foo) Selects only elements containing the text foo. :disabled Selects only form elements that are disabled in the interface (supported by CSS). :enabled Selects only form elements that are enabled in the interface (supported by CSS). :file Selects all file elements (input[type=file]). :header Selects only elements that are headers; for example: <h1> through <h6> elements. :hidden Selects only elements that are hidden. :image Selects form images (input[type=image]). :input Selects only form elements (input, select, textarea, button). :not(filter) Negates the specified filter. :parent Selects only elements that have children (including text), but not empty elements. :password Selects only password elements (input[type=password]). :radio Selects only radio elements (input[type=radio]). :reset Selects reset buttons (input[type=reset] or button[type=reset]). continued on next page Selecting elements for manipulation 29 Many of the custom jQuery selectors are form-related, allowing us to specify, rather elegantly, a specific element type or state. We can combine selector filters too. For example, if we want to select only enabled and checked check boxes, we could use :checkbox:checked:enabled Try out as many of these filters as you like in the Selectors Lab until you feel that you have a good grasp of their operation. These filters are an immensely useful addition to the set of selectors at our dis- posal, but what about the inverse of these filters? Using the :not filter If we want to negate a filter, let’s say to match any input element that’s not a check box, we use the :not filter, which is supported for CSS filters and works with cus- tom jQuery selector filters too. To select non-check box <input> elements, we use input:not(:checkbox) It’s important to recognize the distinction between filter selectors, which attenuate a matching set of elements by applying a further selection criteria to them (like the ones shown previously), and find selectors. Find selectors, such as the descendent selector (space character), the child selector ( > ), and the sibling selector ( + ), find other elements that bear some relationship to the ones already selected, rather than limiting the scope of the match with criteria applied to the matched elements. We can apply the :not filter to filter selectors, but not to find selectors. The selector div p:not(:hidden) is a perfectly valid selector, but div :not(p:hidden) isn’t. :selected Selects option elements that are selected. :submit Selects submit buttons (button[type=submit] or input[type=submit]). :text Selects only text elements (input[type=text]). :visible Selects only elements that are visible. Table 2.3 The jQuery custom filter selectors that give immense power to identify target elements (continued) Selector Description 30 CHAPTER 2 Creating the wrapped element set In the first case, all <p> elements descending from a <div> element that aren’t hidden are selected. The second selector is illegal because it attempts to apply :not to a selector that isn’t a filter (the p in p:hidden isn’t a filter). To make things simpler, filter selectors are easily identified because they all begin with a colon character ( : ) or a square bracket character ( [ ). Any other selec- tor can’t be used inside the :not() filter. As we’ve seen, jQuery gives us a large toolset with which to select existing ele- ments on a page for manipulation via the jQuery methods, which we’ll examine in chapter 3. But before we look at the manipulation methods, let’s see how to use the $() function to create new HTML elements to include in matched sets. “But wait!” as they say, “there’s more!” We’ve emphasized, and will continue to emphasize, that part of jQuery’s strength is the ease with which it allows extensions via plugins. If you’re familiar with using XML Path Language (XPath) to select elements within an Extensible Markup Lan- guage (XML) document, you’re in luck. A jQuery plugin provides some basic XPath support that can be used together with jQuery’s excellent CSS and custom selec- tors. Look for this plugin at http://jquery.com/plugins/project/xpath. Keep in mind that the support for XPath is basic, but it should be enough (in com- bination with everything else we can do with jQuery) to make some powerful selec- tions possible. First, the plugin supports the typical / and // selectors. For example, /html// form/fieldset selects all <fieldset> elements that are directly under a <form> element on the page. We can also use the * selector to represent any element, as in /html//form/*/ input , which selects all <input> elements directly under exactly one element that’s under a <form> element. The XPath plugin also supports the parent selector , which selects parents of previous element selectors. For example: //div/ matches all elements that are directly parent to a <div> element. Also supported are XPath attribute selectors ( //div[@foo=bar] ), as well as con- tainer selectors ( //div[@p] , which selects <div> elements containing at least one <p> element). The plugin also supports position() via the jQuery position selec- tors described earlier. For instance, position()=0 becomes :first , and posi- tion()>n becomes :gt(n) . Generating new HTML 31 2.2 Generating new HTML Sometimes, we’ll want to generate new fragments of HTML to insert into the page. With jQuery, it’s a simple matter because, as we saw in chapter 1, the $ func- tion can create HTML in addition to selecting existing page elements. Consider $("<div>Hello</div>") This expression creates a new <div> element ready to be added to the page. We can run any jQuery commands that we could run on wrapped element sets of existing elements on the newly created fragment. This may not seem impressive on first glance, but when we throw event handlers, Ajax, and effects into the mix (as we will in the upcoming chapters), we’ll see how it can come in handy. Note that if we want to create an empty <div> element, we can get away with a shortcut: $("<div>") As with many things in life, there is a small caveat: we won’t be able to use this technique to reliably create <script> elements. But there are plenty of techniques for handling the situations that would normally cause us to want to build <script> elements in the first place. To give you a taste of what you’ll be able to do later (don’t worry if some of it goes over your head at this point), take a look at this: $("<div class='foo'>I have foo!</div><div>I don't</div>") .filter(".foo").click(function() { alert("I'm foo!"); }).end().appendTo("#someParentDiv"); In this snippet, we first create two <div> elements, one with class foo and one without. We then narrow down the selection to only the <div> with class foo and bind an event handler to it that will fire an alert dialog box when clicked. Finally, we use the end() method (see section 2.3.6) to revert back to the full set of both <div> elements and attach them to the DOM tree by appending them to the ele- ment with the id of someParentDiv . That’s a lot going on in a single statement, but it certainly shows how we can get a lot accomplished without writing a lot of script. An HTML page that runs this example is provided in the downloaded code as chapter2/new.divs.html. Loading this file into a browser results in the displays shown in figure 2.5. On initial load, as seen in the upper portion of figure 2.5, the new <div> ele- ments are created and added to the DOM tree (because we placed the example Identical to $("<div></div>") and $("<div/>") 32 CHAPTER 2 Creating the wrapped element set snippet into the page’s ready handler) right after the element containing text Div 2 (which has the id of someParentDiv ). The lower portion of the figure shows that the defined event handler is triggered when the first newly-created <div> is clicked. Don’t be too worried that we haven’t covered much of what you may need to fully understand the previous example; we’ll get to all of it soon enough. In fact, let’s get right to manipulating the wrapped set, including the filter() command we used in the example. 2.3 Managing the wrapped element set Once we’ve got the set of wrapped elements that we either identified by using a selector to match existing DOM elements or created as new elements using HTML snippets (or a combination of both), we’re ready to manipulate those elements using the powerful set of jQuery commands. We’ll start looking at those com- mands in the next chapter; but what if we’re not quite ready yet? What if we want to further refine the set of elements wrapped by the jQuery function? In this section, we’ll explore the many ways that we can refine, extend, or sub- set the set of wrapped elements that we wish to operate upon. Figure 2.5 New HTML elements can be created under script control and given advanced attributes, such as event handlers, all in a single jQuery statement. Managing the wrapped element set 33 In order to visually help you in this endeavor, another lab page has been set up and included in the downloadable example code for this chapter: the Wrapped Set Lab, which you will find in chapter2/lab.wrapped.set.html. This page, which looks a lot like the Selectors Lab we examined earlier in this chapter, is shown in figure 2.6. This new lab page not only looks like the Selectors Lab, it also operates in a similar fashion. Except in this Lab, rather than typing a selector, we can type in a complete jQuery wrapped set operation. The operation is applied to the DOM Sample, and, as with the Selectors Lab, the results are displayed. In this sense, the Wrapped Set Lab is a more general case of the Selectors Lab. Whereas the latter only allowed us to enter a single selector, the Wrapped Set Lab allows us to enter any expression that results in a jQuery wrapped set. Because of the way jQuery chaining works, this expression can also include com- mands, making this a powerful Lab for examining the operations of jQuery. Be Figure 2.6 The Wrapped Set Lab helps us see how wrapped sets can be created and managed. 34 CHAPTER 2 Creating the wrapped element set aware that you need to enter valid syntax, as well as expressions that result in a jQuery wrapped set. Otherwise, you’re going to be faced with a handful of unhelp- ful JavaScript errors. We’ll see this new Lab in action as we work our way through the sections that follow. 2.3.1 Determining the size of the wrapped set We mentioned before that the set of jQuery wrapped elements acts a lot like an array. This mimicry includes a length property, like JavaScript arrays, that con- tains the number of wrapped elements. Should we wish to use a method rather than a property, jQuery also defines the size() method, which returns the same information. Consider the following statement: $('#someDiv') .html('There are '+$('a').size()+' link(s) on this page.'); The inner jQuery wrapper matches all elements of type <a> and returns the num- ber of matched elements using the size() method. This is used to construct a text string, which is set as the content of an element with id of someDiv using the html() method (which we’ll see in the next chapter). The formal syntax of the size() command is as follows: OK, so now you know how many elements you have. What if you want to access them directly? 2.3.2 Obtaining elements from the wrapped set Usually, once we have a wrapped set of elements, we can use jQuery commands to perform some sort of operation upon them; for example, hiding them all with the hide() method. But there may be times when we want to get our hands on a Command syntax: size size() Returns the count of elements in the wrapped set Parameters none Returns The element count Managing the wrapped element set 35 direct reference to an element or elements to perform raw JavaScript operations upon them. Because jQuery allows us to treat the wrapped set as a JavaScript array, we can use simple array indexing to obtain any element in the wrapped list by position. For example, to obtain the first element in the set of all <img> elements with an alt attribute on the page, we can write $('img[alt]')[0] If we prefer to use a method rather than array indexing, jQuery defines the get() method for that purpose. The fragment $('img[alt]').get(0) is equivalent to the previous example that used array indexing. The get() method can also be used to obtain a plain JavaScript array of all the wrapped elements. Consider: var allLabeledButtons = $('label+button').get(); This statement wraps all the <button> elements on a page that are immediately preceded by <label> elements in a jQuery wrapper and then creates a JavaScript array of those elements to assign to the allLabeledButtons variable. We can use an inverse operation to find the index of a particular element in the wrapped set. Let’s say for some reason we want to know the ordinal index of an image with the id of findMe within the entire set of images in a page. We can obtain this value with var n = $('img').index($('img#findMe')[0]); Command syntax: get get(index) Obtains one or all of the matched elements in the wrapped set. If no parameter is specified, all elements in the wrapped set are returned in a JavaScript array. If an index parameter is provided, the indexed element is returned. Parameters index (Number) The index of the single element to return. If omitted, the entire set is returned in an array. Returns A DOM element or an array of DOM elements. 36 CHAPTER 2 Creating the wrapped element set The syntax of the index() command is as follows: Now, rather than obtaining elements, how would you go about adjusting the set of elements that are wrapped? 2.3.3 Slicing and dicing the wrapped element set Once we have a wrapped element set, we may want to augment that set by adding to it or by reducing the set to a subset of the originally matched elements. jQuery gives us a large collection of methods to manage the set of wrapped elements. First, let’s look at adding elements to a wrapped set. Adding more elements to the wrapped set Often, we may find ourselves in a situation where we want to add more elements to an existing wrapped set. This capability is most useful when we want to add more elements after applying some command to the original set. Remember, jQuery chaining makes it possible to perform an enormous amount of work in a single statement. But first, let’s examine a simple situation. Let’s say that we want to match all <img> elements that have either an alt or a title attribute. The powerful jQuery selectors allow us to express this as a single selector, such as $('img[alt],img[title]') But to illustrate the operation of the add() method, we could match the same set of elements with $('img[alt]').add('img[title]') Using the add() method in this fashion allows us to chain a bunch of selectors together into an or relationship, creating the union of the elements that satisfy both of the selectors. Methods such as add() can also be useful in place of selectors Command syntax: index index(element) Finds the passed element in the wrapped set and returns its ordinal index within the set. If the element isn’t resident in the set, the value -1 is returned. Parameters element (Element) A reference to the element whose ordinal value is to be determined. Returns The ordinal value of the passed element within the wrapped set or -1 if not found. Managing the wrapped element set 37 in that the end() method (which we’ll examine in section 2.3.6) can be used to back out of the elements added via add() . Bring up the Wrapped Set Lab page in your browser, enter the previous exam- ple (exactly as shown), and click the Execute button. This should execute the jQuery operation and result in the selection of all images with either an alt or title attribute. Inspecting the HTML source for the DOM Sample reveals that all the images depicting flowers have alt attributes, the puppy images have title attributes, and the coffee pot image has neither. Therefore, we should expect that all images but the coffee pot would become part of the wrapped set. Figure 2.7 shows a screen capture of the relevant page portions of the results. Command syntax: add add(expression) Adds elements, specified by the expression parameter, to the wrapped set. The expression can be a selector, an HTML fragment, a DOM element, or an array of DOM elements. Parameters expression (String|Element|Array) Specifies what is to be added to the matched set. This parameter can be a jQuery selector, in which case any matched elements are added to the set. If an HTML fragment, the appropriate elements are created and added to the set. If a DOM element or an array of DOM elements, they are added to the set. Returns The wrapped set. Figure 2.7 The expected image elements, those with an alt or title attribute, have been matched by the jQuery expression. [...]... within a jQuery chain of operations Command syntax: find find(selector) Returns a new wrapped set containing all elements of the original set that match the passed selector expression Parameters selector (String) A jQuery selector that elements must match to become part of the returned set Returns The newly created wrapped set In addition to finding elements in a wrapped set that match a selector, jQuery. .. to find elements that contain a specified string The contains() method will return a new wrapped set that consists of all elements that contain the passed string anywhere within its body content Consider $('p').contains('Lorem ipsum') This expression yields a wrapped set containing all paragraphs that contain the text Lorem ipsum Note that the string test is applied to all aspects of the body Managing... markup is read and interpreted by the browser to 50 CHAPTER 3 Bringing pages to life with jQuery create the JavaScript object that represents this element in the DOM In addition to storing the attributes, this object possesses a number of properties, including some that represent the values of the markup attributes (and even one that maintains the list of the attributes themselves) Figure 3. 1 shows a simplified... In this chapter, we covered a lot of ground without doing anything to the DOM elements of the page But now that we know how to select the elements that we want to operate upon, we’re ready to start adding life to our pages with the power of the jQuery commands Bringing pages to life with jQuery This chapter covers: ■ Getting and setting element attributes ■ Manipulating element class names ■ Setting... up to, but not including, the document root prev() Returns a wrapped set consisting of all unique previous siblings of the wrapped elements prevAll() Returns a wrapped set containing all the previous siblings of the wrapped elements siblings() Returns a wrapped set consisting of all unique siblings of the wrapped elements 44 CHAPTER 2 Creating the wrapped element set All of the methods in table 2.4,... element set 45 content, including markup and attribute values of children elements, but it doesn’t match markup or attribute values of the original elements being tested Command syntax: contains contains(text) Returns a new wrapped set composed of elements that contain the text string passed as the text parameter Parameters text (String) The text that an element must contain in order to be added to... Determines if any element in the wrapped set matches the passed selector expression Parameters selector (String) The selector expression to test against the elements of the wrapped set Returns true if at least one element matches the passed selector; false if not 2 .3. 6 Managing jQuery chains We’ve made a big deal (and will continue to do so, because it is a big deal) about the ability to chain jQuery. .. activity in a single statement This chaining ability not only allows us to write powerful operations in a concise manner, but it also improves efficiency because wrapped sets do not have to be recomputed in order to apply multiple commands to them Depending upon the methods used in a command chain, multiple wrapped sets may be generated For example, using the clone() method (which we’ll explore in 46... consisting of all unique next siblings of the wrapped elements nextAll() Returns a wrapped set containing all the following siblings of the wrapped elements parent() Returns a wrapped set consisting of the unique direct parents of all wrapped elements parents() Returns a wrapped set consisting of the unique ancestors of all wrapped elements This includes the direct parents as well as the remaining ancestors... $('*').slice(4); Managing the wrapped element set 43 matches all elements on the page and then returns a set containing all but the first four elements And we’re not done yet! jQuery also gives us the ability to obtain subsets of a wrapped set, based on the relationship of the wrapped items with other elements in the DOM Let’s see how 2 .3. 4 Getting wrapped sets using relationships jQuery allows us to . used within a jQuery chain of operations. In addition to finding elements in a wrapped set that match a selector, jQuery also provides a method to find elements that contain a specified string that results in a jQuery wrapped set. Because of the way jQuery chaining works, this expression can also include com- mands, making this a powerful Lab for examining the operations of jQuery. Be. handlers, all in a single jQuery statement. Managing the wrapped element set 33 In order to visually help you in this endeavor, another lab page has been set up and included in the downloadable