开发者

jQuery: Risk of not closing tags in constructors

开发者 https://www.devze.com 2023-03-03 20:19 出处:网络
Is there any reason I would use $(\'<div></div>\') instead of $(\'<div>\')? Or $(\'<div><b></b></div>\') instead of $(\'<div><b>开发者_开发百科;\'

Is there any reason I would use $('<div></div>') instead of $('<div>')?

Or $('<div><b></b></div>') instead of $('<div><b>开发者_开发百科;')?

I like the latter in both cases because it is shorter.


jQuery automaticcally closes the tags for you, there is no need to close it yourself.

$('<div>') is a perfectly fine thing to do

In that second thing however you are appending the <b> i would do:

$('<div>',{html: $('<b>')}); // or $('<div>').append($('<b>')) 

Fiddle: http://jsfiddle.net/maniator/m9wbb/


I've found edge cases in IE where my code was magically fixed by using $("<div></div>") instead of $("<div>"). I always do this out of paranoia.

I'm sure at some point the jQuery docs specifically said you should close all your tags. This is no longer the case with 1.6 but if your using 1.3.2 or 1.4.2 you may want to close them to be safe.

Although if you look at the source code I would be tempted that for simple tags it is perfectly safe. Do be wary that for complex tags or tags with attributes the source uses .innerHTML so I highly recommend you pass in correctly closed tags.

The source

var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;

...

// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec(selector);

if (ret) {
    if (jQuery.isPlainObject(context)) {
        selector = [document.createElement(ret[1])];
        jQuery.fn.attr.call(selector, context, true);

    } else {
        selector = [doc.createElement(ret[1])];
    }

} else {
    ret = jQuery.buildFragment([match[1]], [doc]);
    selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}   

In this case with $("<div>") you will find that ret[1] is "div" so it calls document.createElement("div").


That depends on whether you use a single tag or multiple tags to create the element/elements.

If you use a single tag, jQuery will use the document.createElement method to create the element, so it doesn't matter if you use "<div/>" or "<div></div>".

If you have several elements, jQuery will create the elements by creating a div element and put the HTML code in the innerHTML property. To get the browser to parse the HTML code properly, you have to write it according to the HTML version you are using. If you are using XHTML for the page, the HTML code that you use to create elements has to be XHTML also.


jQuery does that for you, but consider writing the correct HTML for better readability (the former in the question) :)

0

精彩评论

暂无评论...
验证码 换一张
取 消