Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of managing jQuery packaging set

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail "the management of jQuery packaging set method", the content is detailed, the steps are clear, the details are handled properly, I hope this "management jQuery packaging set method" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

one。 Create elements dynamically

1. Wrong programming method

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

View plaincopy to clipboardprint? Dynamically create an object test layer

In the above example, I dynamically added a div element to the page by modifying the content of testDiv. But remember, this is the wrong thing to do!

The reason for the error:

(1) the structure of the page is changed when the page is loaded. In IE6, if the network slows down or the content of the page is too large, an error will occur to terminate the operation. In other words, "never change the Dom model of a page when it loads."

(2) use modified HTML content to add elements, which does not meet the Dom standard. In practical work, we have also encountered that after using this method to modify content, some browsers can not immediately display the added elements, because different browsers have different display engines. But if we use Dom's CreateElement to create objects, we can do it in almost all browsers. But in jQuery, if you pass in a full HTML string, you also use innerHTML. Therefore, it is not completely negating the use of the innerHTML function.

So from now on, please abandon this old knowledge and use the correct method described below.

two。 Create a new element

Here are two correct ways to create elements.

(1) use HTML DOM to create elements

What is DOM?

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

To change something on the page, JavaScript needs an entry to access all the elements in the HTML document. This entry, along with the methods and attributes that add, move, change, or remove HTML elements, is obtained through the document object model (DOM).

In 1998, the W3C released the first-level DOM specification. This specification allows you to access and manipulate each individual element in a HTML page.

All browsers implement this standard, so DOM compatibility issues are almost impossible 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 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.

This article does not go into details about creating elements using HTML DOM. Here is a simple example:

View plaincopy to clipboardprint? / 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 a Dom element and then add it 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:

$("dynamically created div")

We mainly use one of the methods in the jQuery core class library:

JQuery (html, ownerDocument)

Returns: jQuery

Dynamically create a Dom element based on the HTML original string.

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

When the HTML string is an element with no attributes, internally use document.createElement to create the element, such as:

View plaincopy to clipboardprint? / / jQuery internally uses document.createElement to create elements: $(") .css (" border "," solid 1px # FF0000 ") .html (" dynamically created div ") .appendto (testDiv)

Otherwise, use the innerHTML method to create the element:

View plaincopy to clipboardprint? / / jQuery internally uses innerHTML to create elements: $("dynamically created div") .appendto (testDiv)

3. Add an element to an object

We can use the above two ways to create an element, but it has been mentioned above that you must not change the DOM structure of the page when the page is loaded, such as adding an element. The correct thing to do is to add or remove elements after the page has loaded.

Traditionally, you use _ window.onload to do this:

After view plaincopy to clipboardprint? / / DOM is loaded, add the element / / traditional method _ window.onload = function () {testDiv [XSS _ clean] = "dynamically created div";}

Although it is possible to add new elements after the DOM is fully loaded, unfortunately 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 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 and even execute a script that relies on dynamically added elements before the image is loaded, resulting in script errors.

The solution is to wait for DOM to be parsed and execute our function before images and external resources are loaded. Make this implementation feasible in jQuery:

View plaincopy to clipboardprint? / / jQuery uses the dynamically created $(document) .ready (function) method $(document). Ready (function () {testDiv [XSS _ clean] = "use the dynamically created $(document) .ready (function) method";}) / / or simple syntax: / / jQuery uses the $(function) method $(function () {testDiv [XSS _ clean] + = "use the $(function) method";})

Wrap our function with $(). And can bind multiple functions in a page, if you use the traditional _ window.onload, you can only call one function.

So please use this method to call the function that modifies DOM. Also pay attention to the difference between document.createElement and innerHTML. If possible, try to use document.createElement and $(") to create objects.

three。 Manage jQuery wrapper set elements

Now that we've learned to create elements dynamically, we want to put them 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 wrapper sets:

1. Filter Filtering

Name description example eq (index) gets the nth element to get the matching second element:

$("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 a collection of elements that match the values returned by the specified function

Each object is evaluated once inside this function (as in'$.each'). This element is deleted if the called function returns false, otherwise it will be retained.

Keep elements that do not contain ol in their child elements:

$("div") .filter (function (index) {

Return $("ol", this) .size () = 0

}); is (expr)

Note: this function returns a Boolean value instead of a jQuery wrapper set

Checks the currently selected collection of elements with an expression, and returns true if at least one of the elements matches the given expression.

If no element matches, or if the expression is invalid, return 'false'.' The filter' is actually calling this function internally, so the original rules of the filter () function also apply here.

Because the parent element of the input element is a form element, return true:

$("input [type = 'checkbox']"). Parent (). Is ("form") map (callback) converts a set of elements into another array (whether it is an element array or not)

You can use this function to create a list, whether it's values, properties, CSS styles, or other special forms. This can be easily set up with'$.map ()'.

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

Append ($("input") .map (function () {)

Return $(this) .val ()

}) .get () .join (","); not (expr) removes the element that matches the specified expression removes the element with select's ID from the p element:

$("p") .not ($("# selected") [0]) slice (start, end) selects a matching subset and selects the first p element:

("p") .slice (0,1)

two。 Find Finding

The name description example add (expr) adds elements that match the expression to the jQuery object. This function can be used to join the result set of elements that match two expressions respectively. Dynamically generate an element and add it to the matching element:

$("p") .add ("Again") children ([expr]) gets a collection of elements that contains all the children of each element in the matching set of elements.

You can filter matching child elements through optional expressions. Note: parents () will find all grandparent elements, while children () considers only child elements and not all descendant elements.

Find each child element in DIV:

$("div") .children () closest ([expr]) gets the latest parent element that matches the expression to change the style for the nearest parent class li object of the event source:

$(document) .bind ("click", function (e) {

$(e.target) .closest ("li") .toggleClass ("hilight")

});

Contents () looks for all the child nodes (including text nodes) inside the matching element. If the element is an iframe, look for the contents of the document, find all text nodes and bold:

$("p") .contents () .not ("[nodeType=1]") .wrap ("); find (expr) searches for all elements that match the specified expression. This function is a good way to find out the descendants of the element you are working on.

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

Starting with all the paragraphs, search further for the span element below. Same as $("p span"):

$("p") .find ("span") next ([expr]) gets a collection of elements that contain subsequent sibling elements adjacent to each element in the matching set of elements.

This function only returns the immediately following sibling element, not all subsequent sibling elements (you can use nextAll). You can filter with an optional expression.

Find the peer element immediately after each paragraph:

$("p") .next () nextAll ([expr]) finds all sibling elements after the current element.

You can use expressions to filter

Add a class to all elements after the first div:

$("div:first") .nextAll () .addClass ("after"); offsetParent () returns the first parent class that has a location (such as (relative or absolute)).

Parent ([expr]) gets a collection of elements that contain the unique parent of all matching elements.

You can use optional expressions to filter.

Find the parent element of each paragraph:

$("p") .parent () parents ([expr]) gets a collection of elements containing the ancestor elements of all matching elements (excluding the root element). You can filter through an optional expression. Find all the ancestor elements of each span element:

$("span"). Parents () prev ([expr]) gets a collection of elements containing the previous sibling elements adjacent to each element in the matching set of elements.

You can filter with an optional expression. Only the adjacent peer elements will be matched, not all the previous peer elements.

Find the previous peer element next to each paragraph:

$("p") .prev () prevAll ([expr]) finds all sibling elements before the current element

You can use expressions to filter.

Add a class to all div before the last one:

$("div:last") .prevAll () .addClass ("before") siblings ([expr]) gets a collection of elements that contain all unique siblings of each element in the matching set of elements. You can filter with optional expressions. Find all peer elements for each div:

("div") .siblings ()

3. Series Chaining

Name description example andSelf () adds the previously selected element to the current element

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

Select all div and internal p, and add the border class:

$("div") .find ("p") .andSelf () .addClass ("border"); end () goes back to the most recent "destructive" operation. That is, the list of matching elements is changed to the previous state.

If there is no destructive operation before, an empty set is returned. The so-called "destructive" refers to any operation that changes the matching jQuery element. This includes any function that returns a jQuery object in Traversing-- 'add',' andSelf', 'children',' filter', 'find',' map', 'next',' nextAll', 'not',' parent', 'parents',' prev', 'prevAll',' siblings' and 'slice'-- plus' clone''in Manipulation.

Select all the p elements, find and select the sp child elements, and then select the p elements back:

("p") .find ("span") .end ()

Read here, this "how to manage jQuery packaging set" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more about the article, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report