jQuery: Risk of not closing tags in constructors

。_饼干妹妹 提交于 2019-12-30 18:59:51

问题


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.


回答1:


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.




回答2:


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/




回答3:


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").




回答4:


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



来源:https://stackoverflow.com/questions/5941910/jquery-risk-of-not-closing-tags-in-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!