JQuery HTML API supports parsing and executing JavaScript script functionality implementation-code analysis

Source: Internet
Author: User

JQuery HTML usage (functions like innerHTML)

In development, Ajax technology is needed to update the local area of the page, using AJAX to get an HTML snippet (string), and then use this HTML snippet as an argument to the jquery HTML interface of the target DOM (jquery object), after the statement executes, The HTML snippet is interpreted to perform, showing the page control described by the HTML code snippet. For example:

<HTML><Head>         <Scripttype= "Text/javascript"src= "./jquery.js"></Script>        <style>        </style></Head> <Body>        <Div>Hello world!</Div>         <Scripttype= ' Text/javascript '>            //Suppose Ajaxhtmlstr is an HTML snippet that is obtained through Ajax            varAjaxhtmlstr= "<input type= ' button ' value= ' click me ' >"; $("Div"). HTML (AJAXHTMLSTR); </Script></Body></HTML>

JQuery HTML can parse the execution JS script, why?

HTML interface for the requirements of the contents of the import, can include HTML tag code, or can include JavaScript code snippets (using the <script> tag in the section), the effect is that the HTML tag can be displayed, While JavaScript code can be executed, why is this? What is the way to achieve it?

JS native innerHTML property settings include JS code snippet string, JS code can not be executed. The native JS interface can only execute the JS code through eval, guessing that the HTML implementation is ultimately called this function to execute. The text information in the JS code snippet is parsed out by jquery and then executed.

Test jquery append Add a string including JS code snippet, JS can also be executed.

code example:

<HTML><Head>    <Scriptsrc= "./jquery.js"></Script></Head><Body>    <Divname= "template">        <Select>        </Select>        <inputtype= "button"name= "Testbtn"value= "click me">    </Div>    <Script>        vardivhtml= "<script type= ' text\/javascript ' >console.log (' AA ') <\/script>"; Divhtml+= "<div>aa</div>"; //only HTML segments can be executed, and JavaScript code snippets ignore        //$ ("[name= ' template ']"). Get (0). InnerHTML = divhtml;               //ability to execute HTML, JavaScript code        $("[name= ' template ']"). EQ (0). HTML (divhtml); //ability to execute HTML, JavaScript code        //$ ("[name= ' template ']"). EQ (0). append (divhtml);    </Script></Body></HTML>
jquery implements HTML interface parsing to execute JS script-critical Code Analysis

View jquery source code, analyze HTML interface related implementations

1, the HTML interface is actually, the import parameter value is passed to the access interface, directly call access, access return value is the return value of HTML.
    function (value) {        returnthisfunction(value) {...).
}, NULL, value, arguments.length);

2. Access function analysis

This function is a multifunctional function, which is implemented by the incoming parameter, and other APIs such as the text CSS attr are called by this interface implementation,

The main function is to take the argument FN (a function) to execute on the Elems, and both key and value can be used as arguments for FN execution, return value or Elems.

// multifunctional method to get and set values of a collection // The value/s can optionally be executed if it s a function var function (Elems, FN, key, value, chainable, Emptyget, Raw) {

For the HTML interface to set the HTML code snippet string condition, Access executes the code, the FN action on the Elems, and with the entry parameter value, the following code,

        if (BULK) {            //  Bulk operations run against the entire set            if  (raw) {
    
     fn.call (elems, value);                
     null;

Return to Elems:

    return chainable?          elems :        //  Gets        bulk ?            Fn.call (elems):            ? FN (Elems[0], key): Emptyget;    return chainable?         elems:        //  Gets        bulk?             Fn.call (elems):            ? FN (Elems[0], key): Emptyget;

3. The following is a look at the HTML interface call access, the implementation of the FN function

When the HTML argument is empty, it means getting the HTML code inside the DOM:

            if (Value = = = undefined                ) {return elem.nodetype =                    = = 1? "] ):                    undefined;            }

Judging the HTML snippet, there is no script link and style, it is represented as plain HTML tag code, and the document is updated directly using innerHTML:

            // See If we can take a shortcut and just use InnerHTML            if typeof Value = = = "string" &&! rnoinnerhtml. Test (value) &&                | |!rnoshimcache.test (value)  ) &&                 || !rleadingwhitespace.test (value)) &&                !wrapmap[(rtagname.exec (value) | | [ "", "" ]) [1].tolowercase ()]) {
。。。。
elem.innerhtml = value;
。。。。

If this is not the case, then the empty and append interfaces (also the jquery API) are called, and the HTML snippet is updated to the document:

            if (elem) {                this. Empty (). append (value);            }

The empty implementation is not for our attention, below we focus on append implementation of the JS code to implement the relationship.

4. Append function Analysis

Append implementation, calls the Dommanip function directly, takes the append parameter as the first parameter of the Dommanip function, takes a callback function as the second argument, and returns its return value.

    function () {        returnthisfunction(elem) {            if this  This this. NodeType = = = 9 )                {varThis, elem);                Target.appendchild (Elem);            }        );    },

5, Dommanip Realization Analysis

First, call buildfragment and pass the arguments (HTML snippet string) into the construction of a fragment DOM object, which is out of the document stream and only exists in memory.

        if (l) {            thisfalse this );             = Fragment.firstchild;
    function (elems, context, scripts, selection) {...             = createsafefragment (context),。。。         return safe;    },
Createsafefragment
function Createsafefragment (document) {    var list = Nodenames.split ("|") ),        = document.  Createdocumentfragment ();     if (safefrag.createelement) {        while  (list.length) {            safefrag.createelement (                List.pop ()            );        }    }     return Safefrag;}

Next, this function converts the HTML code to the DOM
                // Convert HTML into DOM nodes                Else {                    = tmp | | safe.appendchild (context.createelement ("div"));                     // deserialize a standard representation                    Tag = (rtagname.exec (elem) | | [ "", "" ]) [1 ].tolowercase ();                     = wrapmap[Tag] | | Wrapmap._default;                    Tmp.   = wrap[1] + elem.replace (rxhtmltag, "<$1></$2>") + wrap[2];

This function then takes the text content of the script Dom node to Eval, and the Support Section understands the cause of the problem.
                            if (NODE.SRC) {                                //  Optional AJAX dependency, but won ' t run scripts if not present                                I F  (Jquery._evalurl) {                                    jquery._evalurl (NODE.SRC);                                }                             Else {                                jQuery.  Globaleval| | node.textcontent | | node.innerhtml | | ""). Replace (Rcleanscript, "") );                            }

JQuery HTML API supports parsing and executing JavaScript script functionality implementation-code analysis

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.