查看 jQuery 库,以下是来自v2.2.0 line 2827 的相关部分。
init = jQuery.fn.init = function(selector, context, root) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if (typeof selector === "string") {
if (selector[0] === "<" &&
selector[selector.length - 1] === ">" &&
selector.length >= 3) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [null, selector, null];
} else {
match = rquickExpr.exec(selector);
}
// Match html or make sure no context is specified for #id
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1]) {
context = context instanceof jQuery ? context[0] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge(this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
));
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for (match in context) {
// Properties of context are called as methods if possible
if (jQuery.isFunction(this[match])) {
this[match](context[match]);
// ...and otherwise set as attributes
} else {
this.attr(match, context[match]);
}
}
}
return this;
您将看到它检查选择器是否为string,如果是,则查看它是否以< 开头并以> 结尾。
if (typeof selector === "string") {
if (selector[0] === "<" &&
selector[selector.length - 1] === ">" &&
selector.length >= 3) {
然后,记住正则表达式 rsingleTag 是:-
var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
同时匹配"<div>" 和"<div />",返回div 作为group[1]。
parseHTML 使用它返回 div 元素,在 merge:-
jQuery.parseHTML = function( data, context, keepScripts ) {
...
var parsed = rsingleTag.exec( data );
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
然后再次使用正则表达式,并将context 作为设置属性的对象:-
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for 用this.attr(match, context[match]); 覆盖每个属性设置
因此,最后将前两个选项之一用于
div?
如上图,个人喜好。两者的工作方式相同。