Learn jquery from scratch (iii) managing the jquery package set

Source: Internet
Author: User

This series of articles navigation

Learn jquery from scratch (i) Getting started with the epoch

Learn jquery from scratch (ii) Universal Selector

Learn jquery from scratch (iii) managing the jquery package set

Learn jquery from scratch (iv) attributes and styles for manipulating elements using jquery

Learn jquery (v) Events and event objects from scratch

Learn about jquery from scratch (vi) Ajax in jquery

Learn jquery (Seven) jquery animation from scratch-Get the page moving!

Learn jquery from scratch (eight): jquery implementation

Learn jquery from scratch (ix) jquery tool functions

Learn jquery from scratch (10) jQueryUI common function combat

Learn jquery from scratch (11) Combat form verification and auto-completion prompt plugin

I. Summary

After we get to the jquery wrapper set using the jquery selector, we need to manipulate it. This chapter first explains how to create elements dynamically, and then learn how to manage the jquery package set, such as adding, deleting, slicing, and so on.

Two. Preface

This series of 2, 3 articles above lists too many API believe that everyone look dizzy. But these foundations must also be said to be solid. In fact, for these lists you can skip, and so on later use to look back or query the official API instructions.

This chapter is very small and focuses on the various functions of dynamically creating elements and manipulating the jquery wrapper set.

Three. Creating elements dynamically 1. Wrong Programming method

We often use JavaScript to dynamically create elements, and many programmers change the HTML content of a container directly by changing it. For example:

<!DOCTYPEHtmlPublic"-//w3c//dtd XHTML 1.0 transitional//en""Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><Htmlxmlns= "Http://www.w3.org/1999/xhtml"><Head><Title> Creating Objects Dynamically</Title></Head><body> <div id= "Testdiv" > test layer </div> <script type= "Text/javascript" Span class= "KWRD" >> document.getElementById ( "Testdiv"). InnerHTML =  "<div Style=\ "Border:solid 1px #FF0000 \" > Dynamically created Div</div> "; </script></ body></html >               

In the example above, I added a DIV element dynamically on the page by modifying the contents of the Testdiv. but keep in mind that this is the wrong thing to do!

Cause of the error:

(1) Changes the structure of the page when the page is loaded. In IE6, if the network slows down or the page content is too large, a "terminate operation" error occurs. This means "never change the DOM model of a page when the page is loaded."

(2) Add elements using the modified HTML content, which does not conform to the DOM standard. In the actual work has also encountered the use of this method to modify content, some browsers do not immediately display the added elements, because the different browser display engine is different. But if we use Dom's createelement to create objects, it's almost always available in all browsers. But in jquery if you pass in a complete HTML string, the interior is also using innerHTML. So it is not entirely negative to use the innerHTML function.

So from now on, discard this old knowledge and program using the correct method described below.

2. Create a new element

Here are two ways to create elements correctly.

(1) Creating elements using the HTML DOM

What is DOM?

With JavaScript, you can refactor the entire HTML document. You can add, remove, change, or rearrange items on a page.

To change something on a page, JavaScript requires access to all the elements in the HTML document. This portal, along with the methods and properties for adding, moving, changing, or removing HTML elements, is obtained through the Document Object Model (DOM).

In 1998, the first level of the DOM specification was published by the consortium. This specification allows access to and manipulation of each individual element in an HTML page.

All browsers have implemented this standard, so the DOM compatibility issue is almost impossible to trace.

The DOM can be used by JavaScript to read, change HTML, XHTML, and XML documents.

The DOM is divided into different sections (core, XML, and HTML) and levels (DOM level 1/2/3):
Core DOM
Defines a standard set of objects for any structured document
Defines a standard set of objects for an XML document
defines a set of standard objects for HTML documents.

About creating elements with HTML DOM this article does not cover the details, here is a simple example:

    Create elements using the DOM standard    var select = document.createelement ("select");    new Option (object = Testdiv.appendchild (select);    

By using the Document.createelement method we can create DOM elements and then add them to the specified object through the AppendChild method.

(2) Creating elements using the jquery function

Creating objects in jquery is simpler, such as creating a DIV element:

$ ("<div style=\" border:solid 1px #FF0000 \ "> Dynamically created Div</div>")

We mainly use one of the methods in the JQuery Core class library:

jQuery (HTML, ownerdocument)
Returns: jQuery

Dynamically creates DOM elements based on HTML raw strings.

Where the HTML parameter is an HTML string, the function has been improved in jQuery1.3.2:

When an HTML string is an element with no attributes, an element is created internally using document.createelement, such as:

jquery internally uses document.createelement to create elements: $ ("<div/>"). CSS ("border","solid 1px #FF0000"). HTML (  "Dynamically created Div"). AppendTo (Testdiv);   

Otherwise, use the innerHTML method to create the element:

jquery internally uses innerHTML to create elements: $ ("<div style=\" border:solid 1px #FF0000 \ "> Dynamically created Div</div>"). AppendTo ( TESTDIV);
3. Adding elements to an object

We can use the above two ways to create an element, but the above mentioned must not change the page when the page load the DOM structure, such as adding an element. It is a good practice to add or remove elements after the page has finished loading.

Traditionally, using window.onload to accomplish the above purposes:

Add the element   "<div style=\" border:solid 1px #FF0000 \ "> Dynamically created Div</div>" after the DOM is loaded;}

Although it is possible to add new elements after the DOM is fully loaded, it is unfortunate that the browser executes the Window.onload function not only after the DOM tree has been built, but also after all images and other external resources have been fully loaded and displayed in the browser window. So if a picture or other resource is loaded for a long time, the visitor will see an incomplete page, or even execute a script that relies on dynamically added elements before the picture is loaded, resulting in a scripting error.

The solution is to wait until the DOM is parsed and execute our functions before the images and external resources are loaded. Make this implementation feasible in jquery:

JQuery uses dynamically created $ (document). Ready (function) method $ (document). Ready (        "<div style=\" Border:solid 1px # Ff0000\ "> Use dynamically created $ (document) method </div>"; });

Or use simple syntax:

JQuery uses the $ (function) method $ (        "<div style=\" border:solid 1px #FF0000 \ "> Use $ (function) method </div>" ; });

Use $ () to wrap up our functions. And you can bind more than one function on a page, and if you use traditional window.onload you can call only one function.

So you will use this method call to modify the DOM function. Also pay attention to the difference between document.createelement and innerHTML. If possible, create objects in the form of Document.createelement and $ ("<div/>").

Four. Managing jquery Package Set elements

Now that you've learned to create elements dynamically, you'll want to put these elements into our jquery packaging set.

We can call these functions on the jquery wrapper set to change our original jquery wrapper set, and most of them return the filtered jquery package set.

jquery provides a series of functions to manage the package set:

1. Filter Filtering
Name Description Example
EQ (Index) Gets the nth element Gets the second element of a match:
$ ("P"). EQ (1)
Filter (expr)

Filters out the collection of elements that match the specified expression.

Keep the elements with the Select class:
$ ("P"). Filter (". Selected")
Filter (FN)

Filters out the collection of elements that match the return value of the specified function

Each object is evaluated within this function once (as ' $.each '). If the called function returns false then this element is deleted, otherwise it will be preserved.

Preserve elements in child elements that do not contain OL:

$ ("div"). Filter (function (index) {
return $ ("ol", this). Size () = = 0;

Is (expr)

Note: This function returns not a jquery wrapper set but a Boolean value

An expression is used to examine the currently selected collection of elements, and returns true if at least one of the elements conforms to the given expression.

Returns ' false ' if no element is met, or if the expression is not valid. The function is actually called inside ' filter ', so the original rule of the filter () function is also applied here.

Because the input element's parent element is a FORM element, it returns true:
$ ("input[type= ' checkbox ']"). Parent (). is ("form")
Map (callback)

Converts a set of elements to another array (whether or not an array of elements)

You can use this function to create a list, whether it's a value, a property, or a CSS style, or any other special form. This can be used ' $.map () ' to facilitate the establishment of

Create a list of values for each INPUT element in the form:

$ ("P"). Append ($ ("input"). Map (function () {
return $ (this). Val ();
}). Get (). Join (","));

Not (expr) To delete an element that matches a specified expression Remove the element with the ID of the select from the P element:
$ ("P"). Not ($ ("#selected") [0])

Slice (start, end)

Select a matching subset Select the first P element:
$ ("P"). Slice (0, 1);
2. Find finding
Name Description Example
Add (expr)

Adds an element that matches an expression to a jquery object. This function can be used to concatenate the result set of an element that matches two expressions respectively.

Dynamically generates an element and adds it to the matching element:
$ ("P"). Add ("<span>Again</span>")
Children ([expr])

Gets a collection of elements that contains all the child elements of each element in the matching element collection.

The matching child elements can be filtered by an optional expression. Note: parents () finds all ancestral elements, whereas children () considers only child elements regardless of all descendant elements.

Find each child element in the DIV:
$ ("div"). Children ()
Closest ([expr]) Gets the most recent parent element that matches the expression

To change the style of the nearest parent class Li object for the event source:

$ (document). Bind ("click", Function (e) {
$ (e.target). Closest ("Li"). Toggleclass ("Hilight");

Contents () Finds all child nodes (including text nodes) within a matching element. If the element is an IFRAME, find the document content Find all text nodes and add bold:
$ ("P"). Contents (). Not ("[nodetype=1]"). Wrap ("<b/>");
Find (expr)

Searches for all elements that match the specified expression. This function is a good way to find out the descendant elements of the element being processed.

All searches are done using jquery expressions. This expression can be written using Css1-3 's selector syntax.

Starting with all the paragraphs, search further for the following span element. Same as $ ("P span"):
$ ("P"). FIND ("span")
Next ([expr])

Gets a collection of elements that contain the next sibling element immediately following each element in the matching element collection.

This function only returns the next sibling element, not all of the siblings behind it (you can use Nextall). You can filter with an optional expression.

Find the sibling elements that are immediately behind each paragraph:
$ ("P"). Next ()
Nextall ([expr])

Finds all sibling elements after the current element.

can be filtered with an expression

Add a class to all elements after the first div:
$ ("Div:first"). Nextall (). addclass ("after");
OffsetParent () Returns the first parent that has a location (for example (relative or absolute)).
Parent ([expr])

Gets a collection of elements that contain the unique parent element for all matching elements.

You can use an optional expression to filter.

Find the parent element for each paragraph:
$ ("P"). Parent ()
Parents ([expr]) Gets a collection of elements containing the ancestor elements of all matching elements (without the root element). You can filter by an optional expression. Find all the ancestor elements of each span element:
$ ("span"). Parents ()
Prev ([expr])

Gets a collection of elements that contain the first sibling element immediately adjacent to each element in the matching element collection.

You can filter with an optional expression. Only the immediate sibling elements are matched to, not all of the preceding sibling elements.

Find the previous sibling element that is adjacent to each paragraph:
$ ("P"). Prev ()
Prevall ([expr])

Finds all sibling elements before the current element

can be filtered with an expression.

Add a class to all the div before the last one:
$ ("Div:last"). Prevall (). addclass ("before");
Siblings ([expr]) Gets a collection of elements that contain all unique sibling elements of each element in the matching element collection. You can filter by using an optional expression. Find all the sibling elements of each div:
$ ("div"). Siblings ()

3. Tandem Chaining

Name Description Example
Andself ()

Join the current element as previously selected

For elements that are filtered or found, it is useful to join the previously selected element.

Select All div and the internal p, plus the Border class:
$ ("div"). Find ("P"). Andself (). addclass ("border");
End () Back to a recent "destructive" operation. That is, the list of matched elements changes to the previous state.

Returns an empty set if there were no previous destructive actions. The so-called "destructive" refers to any action that alters the matching jquery element. This includes any function that returns a JQuery object in traversing--' add ', ' andself ', ' children ', ' filter ', ' find ', ' map ', ' next ', ' Nextall ', ' not ', ' par ' Ent ', ' parents ', ' prev ', ' prevall ', ' siblings ' and ' slice '--plus ' clone ' in manipulation.
Select all the P elements, find and select the span child element, and then return to the P element:

$ ("P"). FIND ("span"). End ()

Five. Examples of commonly used functions


Six. Summary

This article is less content, mainly on how to dynamically create elements and manage the jquery package set, the interface documentation lists too much, the instance part has not yet written. Because to sleep tomorrow also to work, so please forgive me, and so on when there is time to fill up!

Learn jquery from scratch (iii) managing the jquery package set

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.