简体   繁体   中英

Why does jQuery load() use a dummy div internally?

Seen in the jQuery source for the load() function, after the response is received:

        self.html( selector ?

            // If a selector was specified, locate the right elements in a dummy div
            // Exclude scripts to avoid IE 'Permission Denied' errors
            jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :

            // Otherwise use the full result
            responseText );

What is meant by "locate the right elements in a dummy div" ? Why is a dummy div needed at all?

It is not part of the ajax code, but part of the load() method which allows to load a fragment of the response content.

The temp element is created so that when the fragment is queried, if it is the topmost element then that also is fetched else the find() method will exclude the root element. Then you will need to use a combination of filter / find() to do that.

Ex: If the response is <div class="result">....</div> and the selector is .result then if we use $(responseText ).find(selector) , it will fail since the result is not a descendant of the element, but the root, so just adding the response as a descendant of a temp element you have the html as <div><div class="result">....</div></div> , now by just using find('.result') the proper element is returned.

This has to be done if the response is in xmlstring/htmlstring and you can find an element directly in it.

See,

jQuery("<div>")
      .append(jQuery.parseHTML(responseText))
      .find( selector )

Take it line by line:

  1. Create a virtual div in memory to hold the xml/html data.
  2. .append() the xml data as a valid html with jQuery.parseHTML() method.
  3. Now you can find a specific element in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM