Learn jquery from scratch (iii) Manage jquery wrapper set _jquery

Source: Internet
Author: User
Tags html page prev wrapper
I. Summary
After using the jquery selector to get the jquery wrapper set, we need to manipulate it. This chapter first explains how to create elements dynamically, and then learn how to manage jquery wrapper sets, such as additions, deletions, slices, and so on.


two. Foreword
This series of 2, 3, listed above are too many APIs to believe that people look dizzy. However, these foundations must also be said, the foundation should be solid. In fact, for these lists you can skip, and so later when used to look back or check the official API instructions.

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

three. Dynamically creating elements
1. Wrong Programming methods
We often use JavaScript to create elements dynamically, and there are many programmers who change the HTML content of a container directly. For example:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> dynamically Create Objects </title>
<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>

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. A "Terminate operation" error occurs in IE6 if the network slows down or the page content is too large. This means "never change the DOM model of a page when the page is loaded."

(2) Add elements using modified HTML content and do 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 all in all browsers. But in jquery, if you're passing in a complete HTML string, the interior is also using innerHTML. So it's not completely negative about the use of innerHTML functions.

So from now on, please 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 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 needs access to all the elements in the HTML document. This portal, along with methods and properties for adding, moving, changing, or removing HTML elements, is obtained through the Document Object Model (DOM).

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

All browsers implement this standard, so DOM compatibility issues are 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 parts (core, XML, and HTML) and levels (DOM level 1/2/3):
Core DOM
Defines a standard set of objects for any structured document
XML DOM
Defines a standard set of objects for XML documents
HTML DOM
Defines a standard set of objects for HTML documents.
about using the HTML DOM to create an element this article does not give a detailed description, here is a simple example:
Copy Code code as follows:

Creating elements using the DOM standard
var select = Document.createelement ("select");
Select.options[0] = new Option ("Add-in 1", "value1");
SELECT.OPTIONS[1] = new Option ("Add-in 2", "value2");
Select.size = "2";
var object = testdiv.appendchild (select);

By using the Document.createelement method, we can create a DOM element and then add it to the specified object through the AppendChild method.
(2) using the jquery function to create an element
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 a DOM element from an HTML raw string.

Where the HTML parameter is an HTML string, the function is 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:

Copy Code code as follows:

Using document.createelement to create elements within jquery:
$ ("<div/>"). CSS ("border", "solid 1px #FF0000"). HTML ("dynamically created Div"). Appendto (Testdiv);

Otherwise use the innerHTML method to create the element:
Copy Code code as follows:

Using innerHTML to create elements within jquery:
$ ("<div style=\" border:solid 1px #FF0000 \ "> Dynamically created Div</div>"). Appendto (Testdiv);

3. Adding elements to an object
We can create one and element in both of these ways, but it has been mentioned that you must not change the page's DOM structure when the page is loaded, such as adding an element. The right thing to do is to add or remove elements after the page is loaded.
Traditionally, the use of window.onload to accomplish these purposes:
Copy Code code as follows:

Add an element after the DOM has finished loading
Traditional methods
Window.onload = function () {testdiv.innerhtml = "<div style=\" border:solid 1px #FF0000 \ "> Dynamically created Div</div>";}

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 is built, but also after all images and other external resources are loaded completely and after the browser window is displayed. So if a picture or other resource is loaded for a long time, the visitor will see an incomplete page, and even execute a script that relies on dynamically added elements before the picture is loaded, causing the script to be wrong.

The solution is to wait until the DOM is parsed to execute our function before the image and external resources are loaded. Make this implementation feasible in jquery:
Copy Code code as follows:

JQuery uses the dynamically created $ (document). Ready (function) method
$ (document). Ready (
function () {testdiv.innerhtml = "<div style=\ border:solid 1px #FF0000 \" > Using dynamically created $ (document). Ready (function) method </div> "; }
);

Or use simple syntax:
Copy Code code as follows:

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

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

So please use this method to call the function that modifies the DOM. Also pay attention to the difference between document.createelement and innerHTML. If possible, try to create objects using the form document.createelement and $ ("<div/>").
Four. Managing jquery wrapper set elements
Now that you've learned to create elements dynamically, you'll want to put those elements in our jquery wrapper set.

We can call the following functions on the jquery wrapper set to change our original jquery wrapper set, and most of the returns are filtered jquery wrapper sets.

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

1. Filtration Filtering

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

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

Preserve elements with a Select class:
$ ("P"). Filter (". Selected")
Filter (FN)

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

Within this function, each object is evaluated once (as ' $.each '). If the called function returns False, the element is deleted, otherwise it is 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

Checks the collection of currently selected elements with an expression that returns true if at least one of the elements conforms to the given expression.

Returns ' false ' if there is no element conformance, or if the expression is invalid. The inside of ' filter ' is actually calling this function, so the original rule of the filter () function also applies here.

Returns true because the parent element of the INPUT element is a FORM element:
$ ("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 of values, attributes, CSS styles, or other special forms. This can be used ' $.map () ' to facilitate the establishment

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

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

Not (expr) Deletes an element that matches a specified expression To delete an element with the ID of a 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 the jquery object. This function can be used to connect the result sets of elements that match two different expressions.

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

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

You can filter the matched child elements through an optional expression. Note: parents () will look for all ancestral elements, while children () takes into account only child elements, regardless of all descendant elements.

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

Replace style for the closest parent class Li object for the event source:

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

Contents () Finds all child nodes within a matching element, including text nodes. If the element is an IFRAME, find the contents of the document Find all text nodes and 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 the descendant elements of the element being processed.

All searches rely on jquery expressions to complete them. This expression can be written using the Css1-3 selector syntax.

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

Gets a collection of elements that contain a matching set of elements for each of the following sibling elements.

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

Locate the sibling elements immediately following each paragraph:
$ ("P"). Next ()
Nextall ([expr])

Finds all sibling elements after the current element.

You can filter with an expression

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

Gets a collection of elements that contains the unique parent element of 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 that contain the ancestor elements of all matching elements (without the root element). You can filter by an optional expression. Find all ancestor elements for each span element:
$ ("span"). Parents ()
Prev ([expr])

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

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

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

Finds all sibling elements before the current element

You can filter 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 the unique sibling elements of each element in a matching set of elements. You can filter with an optional expression. Find all sibling elements for each div:
$ ("div"). Siblings ()

3. Series Chaining

The
name description example
Andself ( The Join the previously selected join current element

is useful when you want to join the previously selected element when you filter or find the element.

$ ("div"). Find ("P"). Andself (). addclass (" Border ");
End ()
Returns an empty set if the previous action is not destructive. The so-called "destructive" means any action that alters the matching jquery element. This includes any functions that return 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.

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

Five. Examples of commonly used functions
adjourned


Six. Summary
This article is less about how to create elements dynamically and manage the jquery wrapper set, the interface document lists too many instances that have not yet been written. Because to sleep tomorrow to work, so please forgive me, and later when there is time to fill up!
Author: Zhang Zixiu
Source: http://www.cnblogs.com/zhangziqiu/
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.