首页 > 语言 > JavaScript > 正文

jQuery选择器源码解读(一):Sizzle方法

2024-05-06 16:17:53
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了jQuery选择器源码解读(一):Sizzle方法,本文用详细的注释解读了Sizzle方法的实现源码,需要的朋友可以参考下

对jQuery的Sizzle各方法做了深入分析(同时也参考了一些网上资料)后,将结果分享给大家。我将采用连载的方式,对Sizzle使用的一些方法详细解释一下,每篇文章介绍一个方法。

若需要转载,请写明出处,多谢。
 

  1. /* 
  2. * Sizzle方法是Sizzle选择器包的主要入口,jQuery的find方法就是调用该方法获取匹配的节点 
  3. * 该方法主要完成下列任务: 
  4. * 1、对于单一选择器,且是ID、Tag、Class三种类型之一,则直接获取并返回结果 
  5. * 2、对于支持querySelectorAll方法的浏览器,通过执行querySelectorAll方法获取并返回匹配的DOM元素 
  6. * 3、除上之外则调用select方法获取并返回匹配的DOM元素 
  7. *  
  8. *  
  9. * @param selector 选择器字符串 
  10. * @param context 执行匹配的最初的上下文(即DOM元素集合)。若context没有赋值,则取document。 
  11. * @param results 已匹配出的部分最终结果。若results没有赋值,则赋予空数组。 
  12. * @param seed 初始集合 
  13. */ 
  14. function Sizzle(selector, context, results, seed) { 
  15. var match, elem, m, nodeType, 
  16. // QSA vars 
  17. i, groups, old, nid, newContext, newSelector; 
  18.  
  19. /* 
  20. * preferredDoc = window.document 
  21. *  
  22. * setDocument方法完成一些初始化工作 
  23. */ 
  24. if ((context ? context.ownerDocument || context : preferredDoc) !== document) { 
  25. setDocument(context); 
  26. } 
  27.  
  28. context = context || document; 
  29. results = results || []; 
  30.  
  31. /* 
  32. * 若selector不是有效地字符串类型数据,则直接返回results 
  33. */ 
  34. if (!selector || typeof selector !== "string") { 
  35. return results; 
  36. } 
  37.  
  38. /* 
  39. * 若context既不是document(nodeType=9),也不是element(nodeType=1),那么就返回空集合 
  40. */ 
  41. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) { 
  42. return []; 
  43. } 
  44.  
  45. // 若当前过滤的是HTML文档,且没有设定seed,则执行if内的语句体 
  46. if (documentIsHTML && !seed) { 
  47.  
  48. /*  
  49. * 若选择器是单一选择器,且是ID、Tag、Class三种类型之一,则直接获取并返回结果 
  50. *  
  51. * rquickExpr = /^(?:#([/w-]+)|(/w+)|/.([/w-]+))$/ 
  52. * 上述正则表达式括号内三段依次分别用来判断是否是ID、TAG、CLASS类型的单一选择器 
  53. * 上述正则表达式在最外层圆括号内有三个子表达式(即三个圆括号括起来的部分), 
  54. * 分别代表ID、Tag、Class选择器的值,在下面代码中,分别体现在match[1]、match[2]、match[3] 
  55. */ 
  56. if ((match = rquickExpr.exec(selector))) { 
  57. // Speed-up: Sizzle("#ID") 
  58. // 处理ID类型选择器,如:#ID 
  59. if ((m = match[1])) { 
  60. // 若当前上下文是一个document,则执行if内语句体 
  61. if (nodeType === 9) { 
  62. elem = context.getElementById(m); 
  63. // Check parentNode to catch when Blackberry 4.6 
  64. // returns 
  65. // nodes that are no longer in the document #6963 
  66. if (elem && elem.parentNode) { 
  67. // Handle the case where IE, Opera, and Webkit 
  68. // return items 
  69. // by name instead of ID 
  70. /* 
  71. * 一些老版本的浏览器会把name当作ID来处理, 
  72. * 返回不正确的结果,所以需要再一次对比返回节点的ID属性 
  73. */ 
  74. if (elem.id === m) { 
  75. results.push(elem); 
  76. return results; 
  77. } 
  78. } else { 
  79. return results; 
  80. } 
  81. } else { 
  82. // Context is not a document 
  83. /* 
  84. * contains(context, elem)用来确认获取的elem是否是当前context对象的子对象 
  85. */ 
  86. if (context.ownerDocument 
  87. && (elem = context.ownerDocument.getElementById(m)) 
  88. && contains(context, elem) && elem.id === m) { 
  89. results.push(elem); 
  90. return results; 
  91. } 
  92. } 
  93.  
  94. // Speed-up: Sizzle("TAG") 
  95. // 处理Tag类型选择器,如:SPAN 
  96. } else if (match[2]) { 
  97. push.apply(results, context.getElementsByTagName(selector)); 
  98. return results; 
  99.  
  100. // Speed-up: Sizzle(".CLASS") 
  101. /* 
  102. * 处理class类型选择器,如:.class 
  103. * 下面条件判断分别是: 
  104. * m = match[3]:有效的class类型选择器 
  105. * support.getElementsByClassName 该选择器的div支持getElementsByClassName 
  106. * context.getElementsByClassName 当前上下文节点有getElementsByClassName方法 
  107. *  
  108. */ 
  109.  
  110. } else if ((m = match[3]) && support.getElementsByClassName 
  111. && context.getElementsByClassName) { 
  112. push.apply(results, context.getElementsByClassName(m)); 
  113. return results; 
  114. } 
  115. } 
  116.  
  117. // QSA path 
  118. /* 
  119. * 若浏览器支持querySelectorAll方法且选择器符合querySelectorAll调用标准,则执行if内语句体 
  120. * 在这里的检查仅仅是简单匹配 
  121. * 第一次调用Sizzle时,rbuggyQSA为空 
  122. *  
  123. * if语句体内对当前context对象的id的赋值与恢复,是用来修正querySelectorAll的一个BUG 
  124. * 该BUG会在某些情况下把当前节点(context)也作为结果返回回来。 
  125. * 具体方法是,在现有的选择器前加上一个属性选择器:[id=XXX], 
  126. * XXX 为context的id,若context本身没有设置id,则给个默认值expando。 
  127. */ 
  128.  
  129. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) { 
  130. nid = old = expando; 
  131. newContext = context; 
  132. // 若context是document,则newSelector取自selector,否则为false 
  133. newSelector = nodeType === 9 && selector; 
  134.  
  135. // qSA works strangely on Element-rooted queries 
  136. // We can work around this by specifying an extra ID on the 
  137. // root 
  138. // and working up from there (Thanks to Andrew Dupont for 
  139. // the technique) 
  140. // IE 8 doesn't work on object elements 
  141. if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") { 
  142. groups = tokenize(selector); 
  143.  
  144. if ((old = context.getAttribute("id"))) { 
  145. /* 
  146. * rescape = /'|///g, 
  147. * 这里将old中的单引号、竖杠、反斜杠前加一个反斜杠 
  148. * old.replace(rescape, "//#FormatTableID_0#amp;")代码中的#FormatTableID_0#amp;代表匹配项 
  149. */ 
  150. nid = old.replace(rescape, "//#FormatTableID_0#amp;"); 
  151. } else { 
  152. context.setAttribute("id", nid); 
  153. } 
  154. nid = "[id='" + nid + "'] "; 
  155.  
  156. // 重新组合新的选择器 
  157. i = groups.length; 
  158. while (i--) { 
  159. groups[i] = nid + toSelector(groups[i]); 
  160. } 
  161. /* 
  162. * rsibling = new RegExp(whitespace + "*[+~]") 
  163. * rsibling用于判定选择器是否存在兄弟关系符 
  164. * 若包含+~符号,则取context的父节点作为当前节点 
  165. */ 
  166. newContext = rsibling.test(selector) && context.parentNode 
  167. || context; 
  168. newSelector = groups.join(","); 
  169. } 
  170.  
  171. if (newSelector) { 
  172. /* 
  173. * 这里之所以需要用try...catch, 
  174. * 是因为jquery所支持的一些选择器是querySelectorAll所不支持的, 
  175. * 当使用这些选择器时,querySelectorAll会报非法选择器, 
  176. * 故需要jquery自身去实现。 
  177. */ 
  178. try { 
  179. // 将querySelectorAll获取的结果并入results,而后返回resulsts 
  180. push.apply(results, newContext 
  181. .querySelectorAll(newSelector)); 
  182. return results; 
  183. } catch (qsaError) { 
  184. } finally { 
  185. if (!old) { 
  186. context.removeAttribute("id"); 
  187. } 
  188. } 
  189. } 
  190. } 
  191. } 
  192.  
  193. // All others 
  194. // 除上述快捷方式和调用querySelectorAll方式直接获取结果外,其余都需调用select来获取结果 
  195. /* 
  196. * rtrim = new RegExp("^" + whitespace + "+|((?:^|[^////])(?:////.)*)" 
  197. * + whitespace + "+$", "g"), 
  198. * whitespace = "[//x20//t//r//n//f]"; 
  199. * 上述rtrim正则表达式的作用是去掉selector两边的空白,空白字符由whitespace变量定义 
  200. * rtrim的效果与new RegExp("^" + whitespace + "+|" + whitespace + "+$", "g")相似 
  201. */ 
  202. return select(selector.replace(rtrim, "$1"), context, results, seed); 
  203. } 

各位朋友,若觉得写得不错,帮我顶一下,给点动力,多谢
!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选