Learning jQuery from scratch (3) Managing jQuery packaging Sets

Source: Internet
Author: User
Document directory
  • 1. Filter Filtering
  • 2. Find Finding

I. Summary
After getting the jQuery package set using the jQuery selector, We need to operate on it. this chapter describes how to dynamically create elements and how to manage jQuery packaging sets, such as adding, deleting, and slicing.

Ii. Preface
I have listed too many APIs in article 2 and 3 of this series. however, these foundations must be well-founded. in fact, you can skip this list and wait for it to be used to look back or query the official API description.

This chapter has very little content. It mainly describes how to dynamically create elements and operate functions in the jQuery package set.

3. dynamically create elements
1. Incorrect Programming Method
We often use javascript to dynamically create elements. Many programmers directly change the HTML content of a container. For example:Copy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> dynamically create an object </title>
</Head>
<Body>
<Div id = "testDiv"> test layer </div>
<Script type = "text/javascript">
Document. getElementById ("testDiv"). innerHTML = "<div style = \" border: solid 1px # FF0000 \ "> dynamically created div </div> ";
</Script>
</Body>
</Html>

In the above example, I added a div element dynamically on the page by modifying the content of testDiv. But remember that this is an incorrect practice!

Cause of error:

(1) The structure of the page is changed during page loading. in IE6, if the network slows down or the page content is too large, the "stop operation" error will occur. that is to say, "Never change the Dom model of a page during page loading ".

(2) Adding Elements Using Modified HTML content does not comply with Dom standards. in actual work, after using this method to modify the content, Some browsers cannot immediately display the added elements, because the display engines of different browsers are different. however, if we use the CreateElement of Dom to create an object, almost all browsers can. however, if jQuery is passed in as a complete HTML string, innerHTML is also used internally. therefore, the use of the innerHTML function is not completely negative.

So from now on, Please discard this old knowledge and use the correct programming method described below.

2. Create New Elements
The following describes two methods for creating elements.

(1) Use html dom to create elements
What is DOM?

JavaScript allows you to refactor the entire HTML document. You can add, remove, change, or rearrange projects on the page.

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

In 1998, W3C released the first level DOM specification. This specification allows access and operation of each individual element in an HTML page.

All browsers have implemented this standard, so the compatibility of DOM is almost difficult to find.

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

DOM is divided into different parts (core, XML and HTML) and levels (DOM Level 1/2/3 ):
Core DOM
Defines a set of standard objects for any structured document
XML DOM
Defines a set of standard objects for XML documents
HTML DOM
Defines a set of standard HTML document objects.
This article does not detail how to create elements using html dom. The following is a simple example:Copy codeThe Code is as follows: // use the Dom standard to create elements
Var select = document. createElement ("select ");
Select. options [0] = new Option ("add-on 1", "value1 ");
Select. options [1] = new Option ("add-on 2", "value2 ");
Select. size = "2 ";
Var object = testDiv. appendChild (select );

By using the document. createElement method, we can create Dom elements and add them to the specified object through the appendChild method.
(2) Use the jQuery function to create elements
It is easier to create objects in jQuery, such as creating a Div element:
$ ("<Div style = \" border: solid 1px # FF0000 \ "> dynamically created div </div> ")
We mainly use a method in the jQuery core Class Library:

JQuery (html, ownerDocument)
Returns:JQuery

Dynamically create Dom elements based on the original HTML string.

Here, the html parameter is an HTML string, which is improved in jQuery1.3.2:

When the HTML string is an element without attributes, the document. createElement is used internally to create elements, for example:

Copy codeThe Code is as follows: // jQuery uses document. createElement to create an element internally:
$ ("<Div/>" bar .css ("border", "solid 1px # FF0000" bar .html ("dynamically created div"). appendTo (testDiv );

Otherwise, use the innerHTML method to create elements:Copy codeThe Code is as follows: // jQuery internally uses innerHTML to create elements:
$ ("<Div style = \" border: solid 1px # FF0000 \ "> dynamically created div </div>"). appendTo (testDiv );

3. Add the element to the object
We can use the above two methods to create one element, but as mentioned above, do not change the DOM structure of the page during page loading, such as adding an element. the correct method is to add or delete elements after the page is loaded.
Traditionally, window. onload is used for the above purpose:Copy codeThe Code is as follows: // Add an element after the DOM is loaded.
// Traditional Method
Window. onload = function () {testDiv. innerHTML = "<div style = \" border: solid 1px # FF0000 \ "> dynamically created div </div> ";}

Although the new elements can be added after the DOM is fully loaded, unfortunately, the Browser executes the window. the onload function is not only after the DOM tree is built, but also after all the images and other external resources are fully loaded and displayed in the browser window. therefore, if an image or other resources is loaded for a long time, visitors will see an incomplete page, even a script that depends on the dynamically added element is executed before the image is loaded, resulting in a script error.

The solution is to execute our function before the image and external resources are loaded after the DOM is parsed. In jQuery, this implementation is feasible:Copy codeThe Code is as follows: // jQuery uses the dynamically created $ (document). ready (function) Method
$ (Document). ready (
Function () {testDiv. innerHTML = "<div style = \" border: solid 1px # FF0000 \ "> Use dynamically created $ (document ). ready (function) method </div> ";}
);

Or use the simple Syntax:Copy codeThe Code is as follows: // jQuery uses the $ (function) method.
$ (
Function () {testDiv. innerHTML + = "<div style = \" border: solid 1px # FF0000 \ "> use the $ (function) method </div> ";}
);

Use $ () to wrap our functions. You can bind multiple functions to a page. If you use traditional window. onload, you can only call one function.

So please use this method to call the function that modifies the DOM. pay attention to document. differences between createElement and innerHTML. if possible, try to use document. createElement and $ ("<div/>") to create an object.
Iv. Manage jQuery package set Elements
Now that you have learned how to dynamically create elements, you will want to put these elements into our jQuery packaging set.

We can call the following functions in the jQuery packaging set to change our original jQuery packaging set, and most of the returned results are filtered jQuery packaging sets.

JQuery provides a series of functions to manage the packaging set:

1. Filter Filtering

Name Description Example
Eq (index) Obtain the nth Element Obtain the Second Matching Element:
$ ("P"). eq (1)
Filter (expr)

Filters out a set of elements that match the specified expression.

Retain the elements with the select class:
$ ("P"). filter (". selected ")
Filter (fn)

Filters out a set of elements that match the specified function return value.

This function will calculate each object once (as in '$. each'). If the called function returns false, this element will be deleted, otherwise it will be retained.

The reserved sub-element does not contain ol elements:

$ ("Div"). filter (function (index ){
Return $ ("ol", this). size () = 0;
});

Is (expr)

Note: This function returns a Boolean value instead of a jQuery package set.

Use an expression to check the selected element set. If at least one element matches the given expression, true is returned.

If no element matches, or the expression is invalid, 'false'. 'filter' is actually called internally. Therefore, the original rules of the filter () function are also applicable here.

Returns true because the parent element of an input element is a form element:
$ ("Input [type = 'checkbox']"). parent (). is ("form ")
Map (callback)

Convert a group of elements into other arrays (whether or not they are element arrays)

You can use this function to create a list, whether it is a value, attribute, CSS style, or other special form. You can use '$. map ()' to easily create

Create a list of values of each input element in form:

$ ("P"). append ($ ("input"). map (function (){
Return $ (this). val ();
}). Get (). join (","));

Not (expr) Deletes an element that matches the specified expression. Delete an element with a select ID from element p:
$ ("P"). not ($ ("# selected") [0])

Slice (start, end)

Select a matched subset Select the first p element:
$ ("P"). slice (0, 1 );
2. Find Finding

Name Description Example
Add (expr)

Add the elements matching the expression to the jQuery object. This function can be used to connect the element result set that matches the two expressions respectively.

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

Obtains the element set of all child elements of each element in a matched element set.

You can use an optional expression to filter matched child elements. Note: parents () searches for all ancestor elements, while children () only considers child elements, not all descendant elements.

Find each child element in the DIV:
$ ("Div"). children ()
Closest ([expr]) Obtain the latest parent element matching the expression.

Change the style of the parent class li object closest to the event Source:

$ (Document). bind ("click", function (e ){
Criteria (e.tar get). closest ("li"). toggleClass ("hilight ");
});

Contents () Search for all child nodes (including text nodes) within the matching element ). If the element is an iframe, search for the document content Search for all text nodes and bold them:
$ ("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 the child element of the element being processed.

All searches rely on jQuery expressions. This expression can be written using the selector syntax of the CSS1-3.

Search for the following span element from all paragraphs. Same as $ ("p span:
$ ("P"). find ("span ")
Next ([expr])

Obtains the Element Set of the Peer element next to each element in a matched element set.

This function only returns the next peer element, instead of all peer elements (nextAll can be used ). You can use an optional expression for filtering.

Find the peer element next to each paragraph:
$ ("P"). next ()
NextAll ([expr])

Find all peer elements after the current element.

You can use expressions to filter data.

Add a class to all elements after the first div:
$ ("Div: first"). nextAll (). addClass ("after ");
OffsetParent () Returns the first parent class with a location (such as relative or absolute )).
Parent ([expr])

Obtains a set of elements that contain the unique parent element of all matching elements.

You can use an optional expression to filter data.

Find the parent element of each paragraph:
$ ("P"). parent ()
Parents ([expr]) Obtains a set of elements (excluding the root element) that contain all the ancestor elements matching the elements ). You can use an optional expression to filter data. Find all the ancestor elements of each span element:
$ ("Span"). parents ()
Prev ([expr])

Obtains the Element Set of the first peer element next to each element in a matched element set.

You can use an optional expression for filtering. Only peer elements that are adjacent to each other will be matched, instead of all peer elements.

Find the first peer element next to each paragraph:
$ ("P"). prev ()
PrevAll ([expr])

Find all peer elements before the current element

You can use expressions to filter data.

Add a class to all previous divs:
$ ("Div: last"). prevAll (). addClass ("before ");
Siblings ([expr]) Obtains the element set of all unique peer elements of each element in a matched element set. You can use an optional expression for filtering. Find all peer elements of each div:
$ ("Div"). siblings ()

3. Connect Chaining

Name Description Example
AndSelf ()

Add the previously selected element to the current element

For filtered or searched elements, it is useful to add the previously selected elements.

Select All div and internal p, and add the border class:
$ ("Div"). find ("p"). andSelf (). addClass ("border ");
End () Back to the last "destructive" operation. That is, the list of matched elements is changed to the previous state.

If no destructive operation is performed before, an empty set is returned. The so-called "destructive" refers to the operation of any change to the matching jQuery element. This includes any function in Traversing that returns a jQuery object-'add', 'andself ', 'Children', 'filter', 'Find ', 'map ', 'Next', 'nextall', 'not ', 'parent', 'Parents', 'prev', 'prevall ', 'siblings 'and 'slice' -- add 'clone 'in Manipulation '.

Select All p elements, find and select span sub-elements, and then return to select p elements:

$ ("P"). find ("span"). end ()

5. Examples of common functions
[To be continued]

Vi. Summary
This article has little content. It mainly explains how to dynamically create elements and manage the jQuery package set. The interface documentation lists too many items, and the instance has not been written yet. I want to go to bed and go to work tomorrow, so please forgive me and make up when you are free!
Author: Zhang Ziqiu
Source: http://www.cnblogs.com/zhangziqiu/

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.