【jQuery】jQuery源码学习笔记(一)选择器的初始
看了一下,1.7.2 ,做个笔记。
// Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( 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 = quickExpr.exec( selector ); }
这一段开始的选择器的代码,判断第一个字符是不是'<',最后一个是不是'<',而且长度必须大于3,然后,我想到了appendTo()这个方法,试了一下,果然:
① $('<>1>').appendTo('#msg'); // ok ② $('<b>2</b>').appendTo('#msg'); // ok ③ $('3').appendTo('#msg'); // 不会成功被append到msg盒子里面去,因为它认为前面的内容不是以'<'开头和'>'结尾的,不是html内容,而会被当作选择器来使用。
当上面的③发生后,将执行
else { match = quickExpr.exec( selector ); //quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/ /*来自源码*/ }
于是,将用这段正则判断选择器,是否以#开头或者不是。接下来的:
// HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // 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; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; }
嗯,看经典的了:
elem = document.getElementById( match[2] );
由此可见,用#id选择器,是多么的直接而快速。