jq的选择器流程分析开篇
程序员文章站
2022-04-27 18:33:26
...
本文简单地分析以下jquery的选择器流程:
为了考量jq的版本优化,这篇的代码分析来自jq1.3
/* * @param selector * @param context * @info $的入口 */ var jQuery = window.jQuery = window.$ = function(selector,context){ return new jQuery.fn.init(selector,context); }
var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/; jQuery.fn = jQuery.prototype = { /* * @name init * @param selector * @param context */ init:function(selector,context){ //默认是document selector = selector || document; //selector为DOM Element if(selector.nodeType){ this[0] = selector; this.length = 1; this.context = selector; return this; } //selector为string if(typeof selector === "string"){ //比如#test 返回的match为["#test",undefined,undefined,"test"]; //比如<div id="test">test</div>返回的match为:['<div id="test">test</div>','<div id="test">test</div>','v',undefined]; var match = quickExpr.exec(selector); if(match && (match[1] || !context)){ if(match[1]){ selector = jQuery.clean([match[1]],context); }else{ //$("#ID") var elem = document.getElementById(match[3]); if(elem){ if(elem.id != match [3]){ return jQuery().find(selector); } var ret = jQuery(elem); ret.context = document; ret.selector = selector; return ret; } selector = []; } }else{ //$(expr,[context]) ===> $(content).find(expr) return jQuery(context).find(selector); } }else if(jQuery.isFunction(selector)){ //很多简写的方式:$(function(){}); return jQuery(document).ready(selector); } if(seletor.selector && selector.context){ this.selector = selector.selector; this.context = selector.context; } return this.setArray(jQuery.makeArray(selector)); } }