Home > Web Front-end > JS Tutorial > Analysis of jQuery.clean usage methods and ideas_jquery

Analysis of jQuery.clean usage methods and ideas_jquery

WBOY
Release: 2016-05-16 17:44:15
Original
1559 people have browsed it

1. How to use jQuery.clean
jQuery.clean(elems, context, fragment, scripts);
2. Idea analysis
1. Process the parameter context and make sure it is the document root node document
2. Process the parameter elems array (loop through the array)
2.1. elem is a number, convert it to a string
2.2. elem is an illegal value, jump out of this page Second loop
2.3. elem is a string
2.4. If the string does not have an entity number or html tag, create a text node
2.5. The string is an entity number or html tag

Copy the code The code is as follows:

Create a div element and insert it into the document fragment
Process xhtml style tags
Wrap elem and use the wrapped string as the innerHTML of the div
If the wrapping depth is greater than 1, only the first layer of wrapping elements will be left
Clear the tbody automatically added to the empty table tag in ie6 and 7
Use the blank string at the beginning that is removed in browsers below IE9 as the first text child node of the div element
Reassign elem to the child node collection of the div (nodeList object),
Remove this time The div in the document fragment in the loop keeps the clean div element in the next loop

2.3. If elem is a text node, add it directly to the ret array to be returned, otherwise elem(nodeList Object) merged into the array
 2.4. Fix the bug in IE6 and 7 that the selected status (checked) of the node of type radio and checkbox type is invalid
3. Processing parameter fragment
 3.1. Each node in ret is added to the document fragment fragment
3.2. Extract the script child node in the node and add it to the ret array. The added script position is behind the position of the original parent element
4. Return to ret Array
3. Source code comment analysis
1. Variables and functions used in the function
Copy codeThe code is as follows:

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|"
         "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
     wrapMap = {
         option: [ 1, "" ],
         legend: [ 1, "
", "
" ],
         thead: [ 1, "", "
" ],
         tr: [ 2, "", "
" ],
         td: [ 3, "", "
" ],
         col: [ 2, "", "
" ],
         area: [ 1, "", "" ],
         _default: [ 0, "", "" ]
     },
     rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([w:] )[^>]*)/>/gi,
     rtagName = /<([w:] )/,
     rtbody = /     rhtml = /<|&#?w ;/,
     rleadingWhitespace = /^s /,
     rcheckableType = /^(?:checkbox|radio)$/,
     rscriptType = //(java|ecma)script/i;
 // 设置复选框checkbox或单选框radio表单元素的默认选中状态
 function fixDefaultChecked( elem ) {
     if ( rcheckableType.test( elem.type ) ) {
         elem.defaultChecked = elem.checked;
     }
 }
 // 创建一个安全的文档碎片
 function createSafeFragment( document ) {
     var list = nodeNames.split( "|" ),
     safeFrag = document.createDocumentFragment(); // ie6,7,8浏览器把safeFrage作为HTMLDocument类型
     // 针对ie9以下浏览器
     if ( safeFrag.createElement ) {
         while ( list.length ) {
             safeFrag.createElement(
                 list.pop()
             );
         }
     }
     return safeFrag;
 }
 // 模拟ES5中Array的新功能
 // 该函数API:http://www.css88.com/jqapi-1.8/#p=jQuery.grep
 jQuery.extend({
     grep: function( elems, callback, inv ) {
         var retVal,
             ret = [],
             i = 0,
             length = elems.length;
         inv = !!inv;
         // Go through the array, only saving the items
         // that pass the validator function
         for ( ; i < length; i ) {
             retVal = !!callback( elems[ i ], i );
             if ( inv !== retVal ) {
                 ret.push( elems[ i ] );
             }
         }
         return ret;
     }             
 });

2、源码分析
复制代码 代码如下:

jQuery.extend({
clean: function( elems, context, fragment, scripts ) {
// Declare variables
var i, j, elem, tag, wrap, depth, ; ( !context || typeof context.createDocumentFragment === "undefined" ) {
                                                                                                 0; (elem = elems[i]) != null; i ) {
                  // If elem is a number, convert it to a string 🎜>              elem = "";                                                                    Continue;
}
// Convert html string into DOM nodes
// Convert array items (strings) to DOM nodes
if ( typeof elem === "string" ) {
Text node
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );

                                                                                                                                  . It is of #document-fragment type, below ie9 In the browser, safe is an HTMLDocument type node, and the nodeNames array is empty.      div = context.createElement("div");
                                                                                   col,embed,hr, In addition to the labels of img, input, link, meta, param,
// The label of the label to the end of the label to start and end the label
elem = ELEPLACE (rxhtmltag, "& lt; $ 1 & gt; ");
                                                                                                                                                                                                                       lem ) | | ["", ""] )[1].toLowerCase();
                                                                                                                                                                                                _default;
depth = wrap[0];
div.innerHTML = wrap[1] elem wrap[2];
// Move to the right depth
                                             1. DIV re-assigning the value of the nearest parcel element (ie: including the first layer of parcel element)
While (depth--) {
DIV = DIV.LastChild;
}}
                                                                                                                        if ( ! jQuery.support.tbody ) {
                         // String was a , *may* have spurious(伪造的)
                         // 判断字符串中是否拥有空tbody标签
hasBody = rtbody.test(elem);
// If the outermost label is table and tbody is not manually added to the table,
🎜> tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes:
// String was a bare or
                                     / If there is only one empty THEAD or TFOOT tag in the string
// variable tBody is div.childNodes " && !hasBody ?
                                                        for ( j = tbody.length - 1; j >= 0 ; --j ) {
tfoot tag
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
Automatically clear empty table tags Joined tbody
tbody [ j ].parentNode.removeChild( tbody[ j ] );
                                                                     
                                                                                     // IE completely kills leading whitespace when innerHTML is used >                                                                                                                                                                      >            }
                                                                                                                                                                                                                                                                          ​🎜>                                                                        // Clear the created div element
before looping through the string array items next time div.parentNode.removeChild(div);
// If elem is a DOM node (text node )
if ( elem.nodeType ) {
ret.push( elem );
}
// Merge the nodes in the nodeList object into the returned array
            else {
                                                                                                                                                                                                             .merge( ret, elem );
                                                                                                               = null;
                                                                                                                                                                                        // Reset defaultChecked for any radios and checkboxes A single button, after inserting into other tags, the selected state will fail (the following code fixes this bug)
if (! Jquery.support.appendchecked) {
for (i = 0; (elem = 0; (elem = 0; (elem = 0; ret[i]) != null; i ) {
                                                                                                                    elem.getElementsByTagName != = "undefined" ) {
                                                                                                                                                                                                                              }
// Append elements to a provided document fragment
// Insert each DOM node in the ret array into the provided document fragment
// Extract the script node in the dom node and add it to the ret array , the position is after the index position of its original parent element
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it Executable
// If the ELEM element does not exist or the Type value is JavaScript or is ECMAScript
if (! Elem.type || RScripttype.test (elem.type)) {
// Detach The SCR. IPT and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.parent Node?elem.parentNode.removeChild ( elem ) : elem ) :
                                           fragment.appendChild(                                 = ret[i]) != null; i ) {
                                                                                                                                                                handle embedded scripts
// Add elem elements to document fragments and handle embedded scripts (script tag elements)
fragment.appendChild( elem );
if ( typeof elem.getElement sByTagName !== "undefined ") {> // Handlescript Alters the Dom, so use jquery.merge to enterSure Snapshot Iteration
jstags = jquery.grep (jQuery.merge ([], Elem.GetelementsBytagnam e ("script")), Handlescript) ;
                                                                               // Splice the scripts into ret after their ancestor and advance our index beyond them ret.splice.apply ( ret, [i 1, 0].concat( jsTags ) );
             }
         }
         return ret;
     }
 });
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template