参考版本:1.2.6
从下面启动类中,可以明显看出ready事件的几种写法:
- $('document').ready(function(){});
- $().ready(function(){});
- $(function(){});
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
/// <summary>
/// 1: $(expression, context) - 这个函数接收一个包含 CSS 选择器的字符串,然后用这个字符串去匹配一组元素。
/// 2: $(html) - 根据提供的原始 HTML 标记字符串,动态创建由 jQuery 对象包装的 DOM 元素。
/// 3: $(elements) - 将一个或多个DOM元素转化为jQuery对象。
/// 4: $(callback) - $(document).ready()的简写。
/// </summary>
/// <param name="selector" type="String">
/// 1: expression - 用来查找的表达式。
/// 2: html -用于动态创建DOM元素的HTML标记字符串
/// 3: elements - 用于封装成jQuery对象的DOM元素
/// 4: callback - 当DOM加载完成后,执行其中的函数。
/// </param>
/// <param name="context" type="jQuery">
/// 1: context - (可选) 作为待查找的 DOM 元素集、文档或 jQuery 对象。
/// </param>
/// <returns type="jQuery" />
// Make sure that a selection was provided
// --- 如果没有写selector就会用document代替,经实验$().ready();是可以使用的。
selector = selector || document;
///nodeType 属性可返回节点的类型。
/// 最重要的节点类型是:
/// 元素类型 节点类型
///元素element 1
///属性attr 2
///文本text 3
///注释comments 8
///文档document 9
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector == "string" ) {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] )
selector = jQuery.clean( [ match[1] ], context );
// HANDLE: $("#id")
else {
// --- ID选择器部分
var elem = document.getElementById( match[3] );
// Make sure an element was located
if ( elem ){
// --- 跨浏览器兼容问题:document.getElementById
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id != match[3] )
return jQuery().find( selector );
// Otherwise, we inject the element directly into the jQuery object
return jQuery( elem );
}
selector = [];
}
// HANDLE: $(expr, [context])
// (which is just equivalent to: $(content).find(expr)
} else
return jQuery( context ).find( selector );
// HANDLE: $(function)
// Shortcut for document ready
// --- ready的另外一种写法
} else if ( jQuery.isFunction( selector ) )
return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );
return this.setArray(jQuery.makeArray(selector));
}