导航菜单
首页 >  jQuery  > jQuery()

jQuery()

Creating New Elements

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object:

1$( "

My new text

" ).appendTo( "body" );

For explicit parsing of a string to HTML, use the $.parseHTML() method.

By default, elements are created with an .ownerDocument matching the document into which the jQuery library was loaded. Elements being injected into a different document should be created using that document, e.g., $("

hello iframe

", $("#myiframe").prop("contentWindow").document).

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( "" ) or $( "" ), $( "" ) or $( "" ) — jQuery creates the element using the native JavaScript .createElement() function.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as , , or elements. As a result, the elements inserted may not be representative of the original string passed.

Filtering isn't, however, limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

1$( "" );

Tags that cannot contain elements may be quick-closed or not:

12$( "" );$( "" );

When passing HTML to jQuery(), note that text nodes are not treated as DOM elements. With the exception of a few methods (such as .content()), they are generally ignored or removed. E.g:

12var el = $( "23" ); // returns [, "2", ]el = $( "23 >" ); // returns [, "2", , "3 >"]

This behavior is expected. As of jQuery 1.9.0 (and unless using the jQuery Migrate plugin), jQuery() requires the HTML string to start with a

相关推荐: