---
title: "jquery core 源码分析"
author: "gu6866"
date: "2014-03-01T22:08:07Z"
tags: []
categories: ["Web前端"]
slug: "jquery-core"
draft: false
lastmod: "2014-03-01T22:08:07Z"
id: 2024484
url: "https://premier9527.iteye.com/blog/2024484"
---

0001. \**
0002. * author:prk
0003. * date:2008-08-05
0004. * comment:analeyse the core of jquery1.2.6
0005. \*
0006. \*/
0007. /*
0008. * jQuery
0009. \*
0010. * @VERSION - New Wave Javascript
0011. \*
0012. * Copyright (c) 2008 John Resig (jquery.com) Dual licensed under the MIT
0013. * (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
0014. \*
0015. * $Date: 2008-07-24 01:00:32 +0800 (Thu, 24 Jul 2008) $ $Rev: 5793 $
0016. \*/
0017. // Map over jQuery in case of overwrite
0018. var \_jQuery = window.jQuery,
0019. // Map over the $ in case of overwriteff
0020. \_$ = window.$;
0021. var jQuery = window.jQuery = window.$ = function(selector, context) {
0022. // The jQuery object is actually just the init constructor 'enhanced'
0023. **return** **new** jQuery.fn.init(selector, context);
0024. };
0025. // A simple way to check for HTML strings or ID strings
0026. // (both of which we optimize for)
0027. var quickExpr = /^\[^&lt;]\*(&lt;(.|\\s)+&gt;)\[^&gt;]\*$|^#(\[\\w-]+)$/,
0028. // Is it a simple selector
0029. isSimple = /^.\[^:#\\\[\\.]\*$/,
0030. // Will speed up references to undefined, and allows munging its name.
0031. undefined;
0032. jQuery.fn = jQuery.prototype = {
0033. init : function(selector, context) {
0034. selector = selector || document;// 确定selector存在
0035. // 第一种情况 Handle $(DOMElement)单个Dom 元素，忽略上下文
0036. **if** (selector.nodeType) {
0037. **this**\[0] = selector;
0038. **this**.length = 1;
0039. **return** **this**;
0040. }
0041. **if** (typeof selector == "string") {//selector为string
0042. // Are we dealing with HTML string or an ID?
0043. var match = quickExpr.exec(selector);
0044. // Verify a match, and that no context was specified for #id
0045. **if** (match && (match\[1] || !context)) {
0046. **if** (match\[1])// 第二种情况处理$(html) -&gt; $(array)
0047. selector = jQuery.clean(\[match\[1]], context);
0048. **else** {// 第三种情况：HANDLE: $("#id")//处理$("#id")
0049. var elem = document.getElementById(match\[3]);
0050. // Make sure an element was located
0051. **if** (elem) {
0052. // Handle the case where IE and Opera return items
0053. // by name instead of ID
0054. **if** (elem.id != match\[3])
0055. **return** jQuery().find(selector);// 默认是document.find()
0056. // Otherwise, we inject the element directly into the
0057. // jQuery object
0058. **return** jQuery(elem);
0059. }
0060. selector = \[];
0061. }
0062. } **else**
0063. // 第四种情况：处理$(expr, \[context])==$(content).find(expr)
0064. **return** jQuery(context).find(selector);
0065. } **else** **if** (jQuery.isFunction(selector))
0066. // 第五种情况：处理$(function)七Shortcut for document ready
0067. **return** jQuery(document)\[jQuery.fn.ready ? "ready" : "load"](selector);
0068. // 第六种情况：处理$(elements)
0069. **return** **this**.setArray(jQuery.makeArray(selector));
0070. },
0071. // 当前的版本号
0072. jquery : "@VERSION",
0073. // jquery对象中的元素的个数。jquery像数组。能通过$('p')\[0]去取得Dom对象。
0074. size : function() {
0075. **return** **this**.length;
0076. },
0077. // jquery对象的元素的个数
0078. length : 0,
0079. // 取到本jquery对象的第几个Dom元素，无参数，代表全部的Dom元素
0080. get : function(num) {
0081. **return** num == undefined ? jQuery.makeArray(**this**) : **this**\[num];
0082. },
0083. // 采用jQuery构建新对象，同时引用老对象。
0084. pushStack : function(elems) {
0085. var ret = jQuery(elems);// 构建新的jquery对象
0086. ret.prevObject = **this**;// 保存老的对象的引用
0087. **return** ret;
0088. },
0089. // 把array-like对象的元素全部push当前jquery对象。
0090. setArray : function(elems) {
0091. **this**.length = 0;
0092. Array.prototype.push.apply(**this**, elems);
0093. **return** **this**;
0094. },
0095. // 当前jquery对象中每个元素都执行callback(index,elem)函数
0096. each : function(callback, args) {// 返回this
0097. // 其调用了jQuery的静态方法。prototype中的mothodize是解决这类问题的好方法
0098. **return** jQuery.each(**this**, callback, args);
0099. },
0100. // 找到elem在本jquery对象的位置(index)
0101. index : function(elem) {
0102. var ret = -1;
0103. **return** jQuery.inArray( // 如是jQuery对象就取第一个元素
0104. elem && elem.jquery ? elem\[0] : elem, **this**);
0105. },
0106. // attr(properties)
0107. // 将“名/值”形式的对象设置为所有匹配元素的属性。
0108. // attr(name)
0109. // 取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性，则返回 undefined 。
0110. // attr(key,value)
0111. // 为所有匹配的元素设置一个属性值。$("img").attr("src","test.jpg");
0112. // attr(key,fn)
0113. // 为所有匹配的元素设置一个由这个函数计算的值做属性值。
0114. attr : function(name, value, type) {
0115. var options = name;// 支持"名/值"形式的对象和string
0116. **if** (name.constructor == String)
0117. **if** (value === undefined)
0118. // 调用curCss,attr静态方法返回本对象第一个元素的name的属性值
0119. **return** **this**\[0] && jQuery\[type || "attr"](**this**\[0], name);
0120. **else** {// 设定属性值，把name String 转换成"名/值"对象，便于统一的处理
0121. options = {};
0122. options\[name] = value;
0123. }
0124. **return** **this**.each(function(i) {// 为每个元素的指定的name属性设值
0125. **for** (name in options)
0126. // value=options\[name],可以是Fn(index),this--&gt;each elem
0127. jQuery.attr(type ? **this**.style : **this**, name, jQuery
0128. .prop(**this**, options\[name], type, i, name));
0129. });
0130. },
0131. // css(name)
0132. // 访问第一个匹配元素的样式属性。
0133. // css(name,value)
0134. // 在所有匹配的元素中，设置一个样式属性的值。数字将自动转化为像素值
0135. // css(properties)
0136. // 把一个“名/值对”对象设置为所有匹配元素的样式属性。这是一种在所有匹配的元素上设置大量样式属性的最佳方式。
0137. css : function(key, value) {
0138. **if** ((key == 'width' || key == 'height') && parseFloat(value) &lt; 0)
0139. value = undefined;// 忽略负数
0140. **return** **this**.attr(key, value, "curCSS");// 调用了curCSS方法
0141. },
0142. // text()
0143. // 取得所有匹配元素的内容。结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。
0144. // text(val)
0145. // 设置所有匹配元素的文本内容.与 html() 类似, 但将编码 HTML (将 "&lt;" 和 "&gt;" 替换成相应的HTML实体).
0146. text : function(text) {
0147. **if** (typeof text != "object" && text != **null**)
0148. **return** **this**.empty()// 除去所有的子元素，加上创建的文本节点
0149. .append((**this**\[0] && **this**\[0].ownerDocument || document)
0150. .createTextNode(text));
0151. var ret = "";
0152. jQuery.each(text || **this**, function() {// 所有匹配元素包含的文本内容组合起来
0153. jQuery.each(**this**.childNodes, function() {
0154. **if** (**this**.nodeType != 8)// 8：注释
0155. ret += (**this**.nodeType != 1// 元素的话，递归子元素
0156. ? **this**.nodeValue
0157. : jQuery.fn.text(\[**this**]));
0158. });
0159. });
0160. **return** ret;
0161. },
0162. // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
0163. // 一组用于元素标签包裹操作的函数
0164. // 将所有匹配的元素用单个元素包裹起来
0165. // 这个函数的原理是检查提供的第一个元素并在它的代码结构中找到最上层的祖先元素－－这个祖先元素就是包装元素。
0166. // 这于 '.wrap()' 是不同的，'.wrap()'为每一个匹配的元素都包裹一次。
0167. wrapAll : function(html) {
0168. **if** (**this**\[0])
0169. /*
0170. * &lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;cruel&lt;/p&gt;&lt;p&gt;World&lt;/p&gt;。--&gt;
0171. * $("p").wrapAll("&lt;div&gt;&lt;/div&gt;");--&gt;调用wrapAll的jQuery对象，称：A。有三个元素。
0172. * 第一步:复制生成一个jQuery对象，称：B。得到：&lt;div&gt;&lt;/div&gt;的元素。
0173. * 第二步：把B所有的元素都插在A\[0]元素之前，得到&lt;div&gt;&lt;/div&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;cruel&lt;/p&gt;&lt;p&gt;World&lt;/p&gt;
0174. * 第三步：找到B对象中所有元素的最内面的节点，如&lt;div&gt; &lt;/div&gt;。称：inner Node;
0175. * 第四步：向所有innerNode内部插入A对象的所有元素,得到&lt;div&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;cruel&lt;/p&gt;&lt;p&gt;World&lt;/p&gt;&lt;/div&gt;
0176. \*/
0177. jQuery(html, **this**\[0].ownerDocument).clone().insertBefore(**this**\[0])
0178. .map(function() {// 找到当前元素的最下层的子节点
0179. var elem = **this**;
0180. **while** (elem.firstChild)
0181. elem = elem.firstChild;
0182. **return** elem;
0183. }).append(**this**);// this指是调用wrapAll的jQuery对象。
0184. **return** **this**;
0185. },
0186. // 将每一个匹配的元素的子内容(包括文本节点)用一个HTML结构包裹起来
0187. wrapInner : function(html) {
0188. **return** **this**.each(function() {// 这里包裹的对象是每个元素的对象的contents()
0189. jQuery(**this**).contents().wrapAll(html);
0190. });
0191. },
0192. // 对于当前的jquery对象的每个元素都执行wrapAll(html)
0193. wrap : function(html) {
0194. **return** **this**.each(function() {// 这里包裹的对象是每个元素的对象
0195. jQuery(**this**).wrapAll(html);
0196. });
0197. },
0198. // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
0199. // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
0200. // 该组方法主要是完成把元素插到什么地方，与Ext的DomHelp的功能相似。
0201. // 在一个元素之前，之后，元素的开始，结束位置
0202. // 向每个匹配的元素内部追加内容。
0203. // 这个操作与对指定的元素执行appendChild方法，将它们添加到文档中的情况类似
0204. append : function() {
0205. **return** **this**.domManip(arguments, **true**, **false**, function(elem) {
0206. **if** (**this**.nodeType == 1)
0207. **this**.appendChild(elem);
0208. });
0209. },
0210. // 向每个匹配的元素内部前置内容。
0211. // 这是向所有匹配元素内部的开始处插入内容的最佳方式。
0212. prepend : function() {// elem =arguments的转化集合中的dom元素
0213. **return** **this**.domManip(arguments, **true**, **true**, function(elem) {
0214. **if** (**this**.nodeType == 1)// this=jQuery对象的每个元素（对于tr之类会修正)
0215. **this**.insertBefore(elem, **this**.firstChild);
0216. });
0217. },
0218. // 在每个匹配的元素之前插入内容。
0219. before : function() {
0220. **return** **this**.domManip(arguments, **false**, **false**, function(elem) {
0221. **this**.parentNode.insertBefore(elem, **this**);// this=jQuery对象的每个元素
0222. });
0223. },
0224. // 在每个匹配的元素之后插入内容
0225. after : function() {
0226. **return** **this**.domManip(arguments, **false**, **true**, function(elem) {
0227. **this**.parentNode.insertBefore(elem, **this**.nextSibling);
0228. });
0229. },
0230. // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
0231. // 回到最近的一个"破坏性"操作之前。即，将匹配的元素列表变为前一次的状态。
0232. end : function() {
0233. **return** **this**.prevObject || jQuery(\[]);
0234. },
0235. // 搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。
0236. // 所有搜索都依靠jQuery表达式来完成。这个表达式可以使用CSS1-3的选择器语法来写。
0237. find : function(selector) {
0238. var elems = jQuery.map(**this**, function(elem) {// 找到每个元素的满足的
0239. **return** jQuery.find(selector, elem);
0240. });
0241. **return** **this**.pushStack(/\[^+&gt;] \[^+&gt;]/.test(selector) ? jQuery
0242. .unique(elems) : elems);// 是不是返回不重复的元素？
0243. },
0244. // clone当前对象，events表明是否clone事件
0245. clone : function(events) {
0246. // 对每个元素都进行加工（copy)后的集合重新构建jQuery对象
0247. var ret = **this**.map(function() {
0248. **if** (jQuery.browser.msie && !jQuery.isXMLDoc(**this**)) {
0249. // IE 中cloneNode不能copy 通过attachEvent增加的事件
0250. // 而innserHTML不能copy一些修改过的属性（仅作为属性储存）如input 的name
0251. var clone = **this**.cloneNode(**true**), container = document
0252. .createElement("div");
0253. container.appendChild(clone);
0254. **return** jQuery.clean(\[container.innerHTML])\[0];
0255. } **else**
0256. **return** **this**.cloneNode(**true**);
0257. });
0258. // Need to set the expando to null on the cloned set if it exists
0259. // removeData doesn't work here, IE removes it from the original as well
0260. // this is primarily for IE but the data expando shouldn't be copied
0261. // over in any browser
0262. var clone = ret.find("\*").andSelf().each(function() {
0263. **if** (**this**\[expando] != undefined)
0264. **this**\[expando] = **null**;
0265. });
0266. **if** (events === **true**)// clone所有事件
0267. **this**.find("\*").andSelf().each(function(i) {
0268. **if** (**this**.nodeType == 3)
0269. **return**;
0270. var events = jQuery.data(**this**, "events");
0271. **for** (var type in events)
0272. **for** (var handler in events\[type])
0273. jQuery.event.add(clone\[i], type, events\[type]\[handler],
0274. events\[type]\[handler].data);
0275. });
0276. **return** ret;
0277. },
0278. // 筛选出与指定表达式匹配的元素集合。可以通过函数来筛选当前jQuery对象的
0279. // 元素，还有通过用逗号分隔多个表达式来筛选
0280. filter : function(selector) {// grep，multiFilter的综合
0281. **return** **this**.pushStack(jQuery.isFunction(selector)
0282. && jQuery.grep(**this**, function(elem, i) {
0283. **return** selector.call(elem, i);
0284. }) || jQuery.multiFilter(selector, **this**));
0285. },
0286. // 删除与指定表达式匹配的元素
0287. not : function(selector) {
0288. **if** (selector.constructor == String)// 采用jQuery表达式
0289. **if** (isSimple.test(selector))
0290. **return** **this**.pushStack(jQuery.multiFilter(selector, **this**, **true**));
0291. **else**
0292. // 多表达式要过滤
0293. selector = jQuery.multiFilter(selector, **this**);
0294. var isArrayLike = selector.length// array-like的集合？
0295. && selector\[selector.length - 1] !== undefined
0296. && !selector.nodeType;
0297. **return** **this**.filter(function() {// 过滤掉return false的元素
0298. **return** isArrayLike ? jQuery.inArray(**this**, selector) &lt; 0// this在selector中？
0299. : **this** != selector;
0300. });
0301. },
0302. // 把与表达式匹配的元素添加到jQuery对象中。array(-like)的集合也可以追加进来
0303. add : function(selector) {
0304. **return** **this**.pushStack(jQuery.unique(jQuery.merge(**this**.get(),
0305. typeof selector == 'string' ? jQuery(selector) : jQuery
0306. .makeArray(selector))));
0307. },
0308. // 用一个表达式来检查当前选择的元素集合，如果其中至少有一个元素符合这个给定的表达式就返回true。
0309. is : function(selector) {
0310. **return** !!selector && jQuery.multiFilter(selector, **this**).length &gt; 0;
0311. },
0312. // 检查当前的元素是否含有某个特定的类，如果有，则返回true
0313. hasClass : function(selector) {
0314. **return** **this**.is("." + selector);
0315. },
0316. // 获得第一个匹配元素的当前值。
0317. // 在 jQuery 1.2 中,可以返回任意元素的值了。包括select。如果多选，将返回一个数组，其包含所选的值。
0318. // 设置每一个匹配元素的值。在 jQuery 1.2, 这也可以为select元件赋值
0319. val : function(value) {
0320. **if** (value == undefined) {
0321. **if** (**this**.length) {
0322. var elem = **this**\[0];
0323. **if** (jQuery.nodeName(elem, 'option'))
0324. **return** (elem.attributes.value || {}).specified
0325. ? elem.value
0326. : elem.text;
0327. // We need to handle select boxes special
0328. **if** (jQuery.nodeName(elem, "select")) {
0329. var index = elem.selectedIndex, values = \[], options = elem.options, one = elem.type == "select-one";
0330. // Nothing was selected
0331. **if** (index &lt; 0)
0332. **return** **null**;
0333. // Loop through all the selected options
0334. **for** (var i = one ? index : 0, max = one
0335. ? index + 1
0336. : options.length;i &lt; max; i++) {
0337. var option = options\[i];
0338. **if** (option.selected) {
0339. // Get the specifc value for the option
0340. value = jQuery(option).val();
0341. // We don't need an array for one selects
0342. **if** (one)
0343. **return** value;
0344. // Multi-Selects return an array
0345. values.push(value);
0346. }
0347. }
0348. **return** values;
0349. // Everything else, we just grab the value
0350. } **else**
0351. **return** (**this**\[0].value || "").replace(/\\r/g, "");
0352. }
0353. **return** undefined;
0354. }
0355. **if** (value.constructor == Number)
0356. value += '';
0357. **return** **this**
0358. .each(function() {
0359. **if** (**this**.nodeType != 1)
0360. **return**;
0361. **if** (value.constructor == Array
0362. && /radio|checkbox/.test(**this**.type))
0363. **this**.checked = (jQuery.inArray(**this**.value, value) &gt;= 0 || jQuery
0364. .inArray(**this**.name, value) &gt;= 0);
0365. **else** **if** (jQuery.nodeName(**this**, "select")) {
0366. var values = jQuery.makeArray(value);
0367. jQuery("option", **this**)
0368. .each(function() {
0369. **this**.selected = (jQuery.inArray(**this**.value,
0370. values) &gt;= 0 || jQuery.inArray(
0371. **this**.text, values) &gt;= 0);
0372. });
0373. **if** (!values.length)
0374. **this**.selectedIndex = -1;
0375. } **else**
0376. **this**.value = value;
0377. });
0378. },
0379. // 设置每一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。
0380. // 取得第一个匹配的元素的html内容
0381. html : function(value) {
0382. **return** value == undefined ? (**this**\[0] ? **this**\[0].innerHTML : **null**) : **this**
0383. .empty().append(value);// 去掉子节点，追加value
0384. },
0385. // 将所有匹配的元素替换成指定的HTML或DOM元素。
0386. replaceWith : function(value) {
0387. **return** **this**.after(value).remove();// this.after(value),this没有变
0388. },
0389. // 获取第N个元素 。这个元素的位置是从0算起。
0390. eq : function(i) {
0391. **return** **this**.slice(i, +i + 1);
0392. },
0393. // 代理数组的slice,同样的操作。
0394. slice : function() {
0395. **return** **this**.pushStack(Array.prototype.slice.apply(**this**, arguments));
0396. },
0397. // 对于当前jquery对象中每个元素都进行callback（i,elem)的操作
0398. // 返回新生成的jquery对象。
0399. map : function(callback) {
0400. **return** **this**.pushStack(jQuery.map(**this**, function(elem, i) {
0401. **return** callback.call(elem, i, elem);
0402. }));
0403. },
0404. // 把先前jQuery对象的所有元素加到当前的jQuery对象之中
0405. andSelf : function() {
0406. **return** **this**.add(**this**.prevObject);
0407. },
0408. // data(name,value)
0409. // 在元素上存放数据，同时也返回value。
0410. // 如果jQuery集合指向多个元素，那将在所有元素上设置对应数据。
0411. // 这个函数不用建立一个新的expando，就能在一个元素上存放任何格式的数据，而不仅仅是字符串。
0412. // data(name)
0413. // 返回元素上储存的相应名字的数据，可以用data(name, value)来设定。
0414. // 如果jQuery集合指向多个元素，那将只返回第一个元素的对应数据
0415. data : function(key, value) {
0416. var parts = key.split(".");
0417. parts\[1] = parts\[1] ? "." + parts\[1] : "";
0418. **if** (value === undefined) {// 取值
0419. // 这个特别的方法将会触发指定的事件类型上所有绑定的处理函数。但不会执行浏览器默认动作
0420. var data = **this**.triggerHandler("getData" + parts\[1] + "!",
0421. \[parts\[0]]);
0422. **if** (data === undefined && **this**.length)
0423. data = jQuery.data(**this**\[0], key);
0424. **return** data === undefined && parts\[1] ? **this**.data(parts\[0]) : data;
0425. } **else** { // 设值
0426. **return** **this**.trigger("setData" + parts\[1] + "!", \[parts\[0], value])
0427. .each(function() {
0428. jQuery.data(**this**, key, value);
0429. });
0430. }
0431. },
0432. // 在元素上移除存放的数据
0433. // 与$(...).data(name, value)函数作用相反
0434. removeData : function(key) {
0435. **return** **this**.each(function() {
0436. jQuery.removeData(**this**, key);
0437. });
0438. },
0439. // Dom manipulate操作的函数，对于每个jQuery对象中元素都运行
0440. // 由callback操作args转化成的Dom 元素集合的函数。
0441. domManip : function(args, table, reverse, callback) {
0442. var clone = **this**.length &gt; 1, elems;
0443. // 对当前的jquery对象中每个元素都进行操作
0444. **return** **this**.each(function() {
0445. **if** (!elems) {// 把args 转化为dom元素数组，追加的内容
0446. elems = jQuery.clean(args, **this**.ownerDocument);
0447. **if** (reverse)// 倒序
0448. elems.reverse();
0449. }
0450. var obj = **this**;
0451. // Ie Table不兼容，要进行特殊处理
0452. **if** (table && jQuery.nodeName(**this**, "[table](http://www.alimama.com/membersvc/buyadzone/buy_ad_zone.htm?adzoneid=892989 "table")")// 当前元素是table?
0453. && jQuery.nodeName(elems\[0], "tr"))// 要追加是tr?
0454. obj = **this**.getElementsByTagName("tbody")\[0]// 没有tbody,创建追加
0455. || **this**.appendChild(**this**.ownerDocument
0456. .createElement("tbody"));
0457. var scripts = jQuery(\[]);
0458. jQuery.each(elems, function() {
0459. // 长度大于1，就采用clone。取第一个元素，否则就是本元素
0460. var elem = clone ? jQuery(**this**).clone(**true**)\[0] : **this**;
0461. // 执行所有 scripts 在所有的元素注入之后
0462. **if** (jQuery.nodeName(elem, "script"))
0463. scripts = scripts.add(elem);
0464. **else** {
0465. // 除去内部 scripts，同时保存起来， 为了之后的计算
0466. **if** (elem.nodeType == 1)
0467. scripts = scripts.add(jQuery("script", elem)
0468. .remove());
0469. // 注册元素到document之中
0470. callback.call(obj, elem);
0471. }
0472. });
0473. scripts.each(evalScript);
0474. });
0475. }
0476. };
0477. // Give the init function the jQuery prototype for later instantiation
0478. jQuery.fn.init.prototype = jQuery.fn;
0479. function evalScript(i, elem) {
0480. **if** (elem.src) {// &lt;script src.. 通过ajax调用了
0481. jQuery.ajax( {
0482. url : elem.src,
0483. async : **false**,
0484. dataType : "script"
0485. });
0486. } **else** {// 对于本地的，通过globalEval运行
0487. jQuery
0488. .globalEval(elem.text || elem.textContent || elem.innerHTML
0489. || "");
0490. }
0491. **if** (elem.parentNode)// 除去
0492. elem.parentNode.removeChild(elem);
0493. }
0494. function now() {
0495. **return** +**new** Date;
0496. }
0497. jQuery.extend = jQuery.fn.extend = function() {
0498. var target = arguments\[0] || {}, // 第一个参数是目标
0499. i = 1, length = arguments.length, deep = **false**, options;
0500. **if** (target.constructor == Boolean) {// 第一个参数是bool型的
0501. deep = target;// 深度copy
0502. target = arguments\[1] || {};// target指向第二个参数
0503. i = 2;
0504. }
0505. // target 是string 型的或？
0506. **if** (typeof target != "object" && typeof target != "function")
0507. target = {};
0508. **if** (length == i) {// 只有一个参数？或deep copy 时，两个参数
0509. target = **this**;// 目标为this
0510. --i;
0511. }
0512. **for** (;i &lt; length; i++)
0513. **if** ((options = arguments\[i]) != **null**)
0514. **for** (var name in options) {
0515. var src = target\[name], copy = options\[name];
0516. **if** (target === copy)// 防止死循环
0517. **continue**;
0518. // 深度copy处理，最深为元素
0519. **if** (deep && copy && typeof copy == "object" && !copy.nodeType)
0520. target\[name] = jQuery.extend(deep, src
0521. || (copy.length != **null** ? \[] : {}), copy);
0522. **else** **if** (copy !== undefined)// 直接copy
0523. target\[name] = copy;
0524. }
0525. **return** target;
0526. };
0527. var expando = "jQuery" + now(), uuid = 0, windowData = {},
0528. // exclude the following css properties to add px
0529. exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
0530. // cache defaultView
0531. // defaultViewis generally a reference to the window object for the document
0532. defaultView = document.defaultView || {};
0533. jQuery.extend( {
0534. noConflict : function(deep) {
0535. window.$ = \_$;
0536. **if** (deep)
0537. window.jQuery = \_jQuery;
0538. **return** jQuery;
0539. },
0540. // See test/unit/core.js for details concerning this function.
0541. // Since 1.3 DOM methods and function like alert
0542. // aren't supported. They return false on IE (#2968).
0543. isFunction : function(fn) {
0544. **return** fn **instanceof** Function;
0545. },
0546. // 判断是不是XMLDoc
0547. isXMLDoc : function(elem) {
0548. **return** elem.documentElement && !elem.body || elem.tagName
0549. && elem.ownerDocument && !elem.ownerDocument.body;
0550. },
0551. // Evalulates a script in a global context
0552. // 在全局的范围eval 代码，也就是在&lt;head&gt;&lt;/head&gt;中
0553. globalEval : function(data) {
0554. data = jQuery.trim(data);
0555. **if** (data) {
0556. // Inspired by code by Andrea Giammarchi
0557. // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
0558. var head = document.getElementsByTagName("head")\[0]
0559. || document.documentElement, script = document
0560. .createElement("script");
0561. script.type = "text/javascript";
0562. **if** (jQuery.browser.msie)
0563. script.text = data;
0564. **else**
0565. script.appendChild(document.createTextNode(data));
0566. // Use insertBefore instead of appendChild to circumvent an IE6
0567. // bug. This arises when a base node is used (#2709).
0568. head.insertBefore(script, head.firstChild);
0569. head.removeChild(script);
0570. }
0571. },
0572. // 判断elem的nodeName是否存在
0573. nodeName : function(elem, name) {
0574. **return** elem.nodeName
0575. && elem.nodeName.toUpperCase() == name.toUpperCase();
0576. },
0577. cache : {},
0578. data : function(elem, name, data) {
0579. elem = elem == window ? windowData : elem;
0580. var id = elem\[expando];
0581. // Compute a unique ID for the element
0582. **if** (!id)
0583. id = elem\[expando] = ++uuid;
0584. // Only generate the data cache if we're
0585. // trying to access or manipulate it
0586. **if** (name && !jQuery.cache\[id])
0587. jQuery.cache\[id] = {};
0588. // Prevent overriding the named cache with undefined values
0589. **if** (data !== undefined)
0590. jQuery.cache\[id]\[name] = data;
0591. // Return the named cache data, or the ID for the element
0592. **return** name ? jQuery.cache\[id]\[name] : id;
0593. },
0594. removeData : function(elem, name) {
0595. elem = elem == window ? windowData : elem;
0596. var id = elem\[expando];
0597. // If we want to remove a specific section of the element's data
0598. **if** (name) {
0599. **if** (jQuery.cache\[id]) {
0600. // Remove the section of cache data
0601. delete jQuery.cache\[id]\[name];
0602. // If we've removed all the data, remove the element's cache
0603. name = "";
0604. **for** (name in jQuery.cache\[id])
0605. **break**;
0606. **if** (!name)
0607. jQuery.removeData(elem);
0608. }
0609. // Otherwise, we want to remove all of the element's data
0610. } **else** {
0611. // Clean up the element expando
0612. **try** {
0613. delete elem\[expando];
0614. } **catch** (e) {
0615. // IE has trouble directly removing the expando
0616. // but it's ok with using removeAttribute
0617. **if** (elem.removeAttribute)
0618. elem.removeAttribute(expando);
0619. }
0620. // Completely remove the data cache
0621. delete jQuery.cache\[id];
0622. }
0623. },
0624. // 对object中的每个对象都执行callback函数进行处理。args仅仅内部用
0625. each : function(object, callback, args) {
0626. var name, i = 0, length = object.length;
0627. // 和else的处理差不多，args的传参代替object的属性值
0628. **if** (args) {
0629. **if** (length == undefined) {
0630. **for** (name in object)
0631. **if** (callback.apply(object\[name], args) === **false**)
0632. **break**;
0633. } **else**
0634. **for** (;i &lt; length;)
0635. **if** (callback.apply(object\[i++], args) === **false**)
0636. **break**;
0637. // A special, fast, case for the most common use of each
0638. } **else** {
0639. // 不是array-like的object，对每个属性进行callback函数的调用
0640. **if** (length == undefined) {
0641. **for** (name in object)
0642. **if** (callback.call(object\[name], name, object\[name]) === **false**)
0643. **break**;
0644. } **else**
0645. // array-like object,采用数组的形式来处理
0646. **for** (var value = object\[0];i &lt; length
0647. && callback.call(value, i, value) !== **false**; value = object\[++i]) {
0648. }
0649. }
0650. **return** object;
0651. },
0652. // 根据指定元素(elem)的指定的name来修正value值，如加px,exec Fn.
0653. prop : function(elem, value, type, i, name) {
0654. **if** (jQuery.isFunction(value))// value=Fn
0655. value = value.call(elem, i);// 得到Fn的返回value
0656. // 对于element的style中CSS属性，对需要加上单位的加上px单位
0657. **return** value && value.constructor == Number && type == "curCSS"
0658. && !exclude.test(name) ? value + "px" : value;
0659. },
0660. // 一组内部使用的Class操作函数
0661. className : {
0662. // 为元素增加classNameS
0663. add : function(elem, classNames) {// 多个className,空格分开
0664. jQuery.each((classNames || "").split(/\\s+/),
0665. function(i, className) {
0666. **if** (elem.nodeType == 1
0667. && !jQuery.className.has(elem.className,
0668. className))
0669. elem.className += (elem.className ? " " : "")
0670. + className;
0671. });
0672. },
0673. // 为元素除去classNames
0674. remove : function(elem, classNames) {
0675. **if** (elem.nodeType == 1)// 元素
0676. elem.className = classNames != undefined ? jQuery.grep(
0677. elem.className.split(/\\s+/), function(className) {// 过滤
0678. **return** !jQuery.className.has(classNames,
0679. className);
0680. }).join(" ") : "";
0681. },
0682. // 元素有没有className?
0683. has : function(elem, className) {
0684. **return** jQuery.inArray(className, (elem.className || elem)
0685. .toString().split(/\\s+/)) &gt; -1;
0686. }
0687. },
0688. // 间隔改变elem的样式
0689. swap : function(elem, options, callback) {
0690. var old = {};
0691. **for** (var name in options) {// 替换elem.style中的属性
0692. old\[name] = elem.style\[name];
0693. elem.style\[name] = options\[name];
0694. }
0695. // 执行回调
0696. callback.call(elem);
0697. // 重新换回原来的属性
0698. **for** (var name in options)
0699. elem.style\[name] = old\[name];
0700. },
0701. // 取得elem的name的属性值
0702. css : function(elem, name, force) {
0703. // 对元素的宽度高度修正
0704. **if** (name == "width" || name == "height") {
0705. var val, props = {
0706. position : "absolute",
0707. visibility : "hidden",
0708. display : "block"
0709. }, which = (name == "width" ? \["Left", "Right"] : ["Top",
0710. "Bottom"]);
0711. function getWH() {// 求元素的实现高度，宽度
0712. val = name == "width"
0713. ? elem.offsetWidth
0714. : elem.offsetHeight;
0715. var padding = 0, border = 0;
0716. jQuery.each(which, function() {
0717. // paddinLeft,paddingRight
0718. padding += parseFloat(jQuery.curCSS(elem, "padding"
0719. + **this**, **true**))
0720. || 0;
0721. // borderTopWidth,borderBottomWith
0722. border += parseFloat(jQuery.curCSS(elem, "border"
0723. + **this** + "Width", **true**))
0724. || 0;
0725. });
0726. val -= Math.round(padding + border);
0727. }
0728. **if** (jQuery(elem).is(":visible"))
0729. getWH();
0730. **else**
0731. // 元素看不到的情况下，绝对定位，取高度或宽度
0732. jQuery.swap(elem, props, getWH);
0733. **return** Math.max(0, val);
0734. }
0735. **return** jQuery.curCSS(elem, name, force);
0736. },
0737. curCSS : function(elem, name, force) {
0738. var ret, style = elem.style;
0739. // elem的属性值被破坏
0740. function color(elem) {
0741. **if** (!jQuery.browser.safari)
0742. **return** **false**;
0743. // 从defaultView 取
0744. var ret = defaultView.getComputedStyle(elem, **null**);
0745. **return** !ret || ret.getPropertyValue("color") == "";
0746. }
0747. // IE 中opacity 不兼容
0748. **if** (name == "opacity" && jQuery.browser.msie) {
0749. ret = jQuery.attr(style, "opacity");
0750. **return** ret == "" ? "1" : ret;// 1是100%的显示
0751. }
0752. // Opera的display bug修正, 见 #2037
0753. **if** (jQuery.browser.opera && name == "display") {
0754. var save = style.outline;
0755. style.outline = "0 solid black";
0756. style.outline = save;
0757. }
0758. **if** (name.match(/**float**/i))// float是通过styleFloat取值的
0759. name = styleFloat;
0760. **if** (!force && style && style\[name])
0761. ret = style\[name];// 取值
0762. **else** **if** (defaultView.getComputedStyle) {// 看看defaultView的CSS
0763. **if** (name.match(/**float**/i))
0764. name = "float";
0765. // 转换成lamb,如addMethod变成add-method
0766. name = name.replace(/(\[A-Z])/g, "-$1").toLowerCase();
0767. var computedStyle = defaultView.getComputedStyle(elem, **null**);
0768. **if** (computedStyle && !color(elem))
0769. ret = computedStyle.getPropertyValue(name);
0770. **else** {// Safari没有正确地报道属性值，会提示none elements are involved
0771. var swap = \[], stack = \[], a = elem, i = 0;
0772. // Locate all of the parent display: none elements
0773. **for** (;a && color(a); a = a.parentNode)
0774. stack.unshift(a);
0775. // Go through and make them visible, but in reverse
0776. // (It would be better if we knew the exact display type
0777. // that they had)
0778. **for** (;i &lt; stack.length; i++)
0779. **if** (color(stack\[i])) {
0780. swap\[i] = stack\[i].style.display;
0781. stack\[i].style.display = "block";
0782. }
0783. // Since we flip the display style, we have to handle that
0784. // one special, otherwise get the value
0785. ret = name == "display" && swap\[stack.length - 1] != **null**
0786. ? "none"
0787. : (computedStyle && computedStyle
0788. .getPropertyValue(name))
0789. || "";
0790. // Finally, revert the display styles back
0791. **for** (i = 0;i &lt; swap.length; i++)
0792. **if** (swap\[i] != **null**)
0793. stack\[i].style.display = swap\[i];
0794. }
0795. // We should always get a number back from opacity
0796. **if** (name == "opacity" && ret == "")
0797. ret = "1";
0798. } **else** **if** (elem.currentStyle) {// 元素的currentStyle
0799. var camelCase = name.replace(/\\-(\\w)/g, function(all, letter) {
0800. **return** letter.toUpperCase();
0801. });
0802. ret = elem.currentStyle\[name] || elem.currentStyle\[camelCase];
0803. // From the awesome hack by Dean Edwards
0804. // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
0805. // If we're not dealing with a regular pixel number
0806. // but a number that has a weird ending, we need to convert it
0807. // to pixels
0808. **if** (!/^\\d+(px)?$/i.test(ret) && /^\\d/.test(ret)) {
0809. // Remember the original values
0810. var left = style.left, rsLeft = elem.runtimeStyle.left;
0811. // Put in the new values to get a computed value out
0812. elem.runtimeStyle.left = elem.currentStyle.left;
0813. style.left = ret || 0;
0814. ret = style.pixelLeft + "px";
0815. // Revert the changed values
0816. style.left = left;
0817. elem.runtimeStyle.left = rsLeft;
0818. }
0819. }
0820. **return** ret;
0821. },
0822. // 把html转换成Dom元素,elems多个html string 的数组
0823. clean : function(elems, context) {
0824. var ret = \[];
0825. context = context || document;
0826. // !context.createElement fails in IE with an error but returns
0827. // typeof 'object'
0828. **if** (typeof context.createElement == 'undefined')
0829. // 处理context是jquery对象或数组的兼容。context可以是元素，或元素的集合，或空
0830. context = context.ownerDocument || context\[0]
0831. && context\[0].ownerDocument || document;
0832. jQuery
0833. .each(elems, function(i, elem) {
0834. **if** (typeof elem == 'number')
0835. elem += '';// 把int 转换成string的最高效的方法
0836. **if** (!elem)
0837. **return**;// 为''，undefined,false等时返回
0838. // 转换html为Dom元素
0839. **if** (typeof elem == "string") {
0840. // Fix "XHTML"-style tags in all browsers
0841. // 对于其它的标签，修改成xml的格式
0842. elem = elem
0843. .replace(
0844. /(&lt;(\\w+)\[^&gt;]\*?)\\/&gt;/g,// front=(&lt;(\\w+)\[^&gt;]\*?)
0845. function(all, front, tag) {
0846. **return** tag
0847. .match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)
0848. ? all
0849. : front + "&gt;&lt;/" + tag
0850. + "&gt;";
0851. });
0852. // 去空格，否则indexof可能会出不能正常工作
0853. var tags = jQuery.trim(elem).toLowerCase(), div = context
0854. .createElement("div");
0855. // 有些标签必须是有一些约束的，比如&lt;option&gt;必须在&lt;select&gt;&lt;/select&gt;中间
0856. // 下面的代码在大部分是对&lt;table&gt;中子元素进行修正。数组中第一个元素为深度
0857. var wrap = !tags.indexOf("&lt;opt")
0858. && [1, "&lt;select multiple='multiple'&gt;",
0859. "&lt;/select&gt;"]
0860. || !tags.indexOf("&lt;leg")
0861. && \[1, "&lt;fieldset&gt;", "&lt;/fieldset&gt;"]
0862. || tags
0863. .match(/^&lt;(thead|tbody|tfoot|colg|cap)/)
0864. && \[1, "&lt;table&gt;", "&lt;/table&gt;"]
0865. || !tags.indexOf("&lt;tr")
0866. && \[2, "&lt;table&gt;&lt;tbody&gt;", "&lt;/tbody&gt;&lt;/table&gt;"]
0867. || (!tags.indexOf("&lt;td") || !tags
0868. .indexOf("&lt;th"))
0869. && [3, "&lt;table&gt;&lt;tbody&gt;&lt;tr&gt;",
0870. "&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;"]
0871. || !tags.indexOf("&lt;col")
0872. && [2, "&lt;table&gt;&lt;tbody&gt;&lt;/tbody&gt;&lt;colgroup&gt;",
0873. "&lt;/colgroup&gt;&lt;/table&gt;"]
0874. ||
0875. // IE can't serialize &lt;link&gt; and &lt;script&gt;
0876. // tags normally
0877. jQuery.browser.msie
0878. && \[1, "div&lt;div&gt;", "&lt;/div&gt;"] ||
0879. \[0, "", ""];
0880. // 包裹html之后，采用innerHTML转换成Dom
0881. div.innerHTML = wrap\[1] + elem + wrap\[2];
0882. **while** (wrap\[0]--)
0883. // 转到正确的深度,对于[1, "&lt;table&gt;",
0884. // "&lt;/table&gt;"]，div=&lt;table&gt;
0885. div = div.lastChild;
0886. // fragments去掉IE对&lt;table&gt;自动插入的&lt;tbody&gt;
0887. **if** (jQuery.browser.msie) {
0888. // Tag字符是&lt;table&gt;, \*may\*有伪造的 &lt;tbody&gt;
0889. var tbody = !tags.indexOf("&lt;table")// &lt;table开头
0890. && tags.indexOf("&lt;tbody") &lt; 0// 但没有&lt;tbody
0891. ? div.firstChild// 生成的元素中可能会自动加的&lt;tbody&gt;
0892. && div.firstChild.childNodes :
0893. // String was a bare &lt;thead&gt; or &lt;tfoot&gt;
0894. wrap\[1] == "&lt;table&gt;"
0895. && tags.indexOf("&lt;tbody") &lt; 0// 没有出现&lt;tbody
0896. ? div.childNodes// 没有加&lt;tbody&gt;
0897. : \[];
0898. // 除去&lt;tbody&gt;
0899. **for** (var j = tbody.length - 1;j &gt;= 0; --j)
0900. **if** (jQuery.nodeName(tbody\[j], "tbody")
0901. && !tbody\[j].childNodes.length)
0902. tbody\[j].parentNode
0903. .removeChild(tbody\[j]);
0904. // IE completely kills leading whitespace when
0905. // innerHTML is used
0906. **if** (/^\\s/.test(elem))
0907. div.insertBefore(
0908. context.createTextNode(elem
0909. .match(/^\\s\*/)\[0]),
0910. div.firstChild);
0911. }
0912. elem = jQuery.makeArray(div.childNodes);
0913. }
0914. **if** (elem.length === 0
0915. && (!jQuery.nodeName(elem, "form") && !jQuery
0916. .nodeName(elem, "select")))
0917. **return**;
0918. **if** (elem\[0] == undefined
0919. || jQuery.nodeName(elem, "form")
0920. || elem.options)
0921. ret.push(elem);
0922. **else**
0923. // 对于elems是array-like的集合
0924. ret = jQuery.merge(ret, elem);
0925. });
0926. **return** ret;
0927. },
0928. // 为给定的elem的name属性设定value值
0929. // 或取elem的name属性值
0930. attr : function(elem, name, value) {
0931. // 文本，注释节点不处理
0932. **if** (!elem || elem.nodeType == 3 || elem.nodeType == 8)
0933. **return** undefined;
0934. var notxml = !jQuery.isXMLDoc(elem),
0935. // 取值还是设值？
0936. set = value !== undefined, msie = jQuery.browser.msie;
0937. // 兼容的处理
0938. name = notxml && jQuery.props\[name] || name;
0939. // Only do all the following if this is a node (faster for style)
0940. // IE elem.getAttribute passes even for style
0941. **if** (elem.tagName) {
0942. var special = /href|src|style/.test(name);// 要特殊处理
0943. // 对于safari的特殊处理
0944. **if** (name == "selected" && jQuery.browser.safari)
0945. elem.parentNode.selectedIndex;
0946. **if** (name in elem && notxml && !special) {// 通过DOM 0方式进入属性
0947. **if** (set) {// 改变属性
0948. // IE报错，type不能改变
0949. **if** (name == "type" && jQuery.nodeName(elem, "input")
0950. && elem.parentNode)
0951. **throw** "type property can't be changed";
0952. elem\[name] = value;
0953. }
0954. // 对于attr(form,name)取是form\[name].value
0955. **if** (jQuery.nodeName(elem, "form")
0956. && elem.getAttributeNode(name))
0957. **return** elem.getAttributeNode(name).nodeValue;
0958. // 返回元素的属性值
0959. **return** elem\[name];
0960. }
0961. // 对style进行属性的操作
0962. **if** (msie && notxml && name == "style")
0963. **return** jQuery.attr(elem.style, "cssText", value);
0964. **if** (set)
0965. // IE会报错 see #1070
0966. elem.setAttribute(name, "" + value);
0967. var attr = msie && notxml && special
0968. // Some attributes require a special call on IE
0969. ? elem.getAttribute(name, 2)
0970. : elem.getAttribute(name);
0971. // 不存在的属性返回null,改成undefined
0972. **return** attr === **null** ? undefined : attr;
0973. }
0974. // 当elem参数是elem.style时。。。
0975. // IE 使用 filters for opacity
0976. **if** (msie && name == "opacity") {
0977. **if** (set) {
0978. // IE opacity 要层的支持
0979. elem.zoom = 1;
0980. // 设 alpha filter 来设定 opacity
0981. elem.filter = (elem.filter || "").replace(/alpha\\(\[^)]\*\\)/,
0982. "")
0983. + ((parseInt(value) + '' == "NaN"
0984. ? ""
0985. : "alpha(opacity=" + value * 100 + ")"));
0986. }
0987. **return** elem.filter && elem.filter.indexOf("opacity=") &gt;= 0
0988. ? (parseFloat(elem.filter.match(/opacity=(\[^)]\*)/)\[1]) / 100)
0989. + ''
0990. : "";
0991. }
0992. // lamb字的支持
0993. name = name.replace(/-(\[a-z])/ig, function(all, letter) {
0994. **return** letter.toUpperCase();
0995. });
0996. **if** (set)
0997. elem\[name] = value;
0998. **return** elem\[name];
0999. },
1000. // trim(text)
1001. trim : function(text) {
1002. **return** (text || "").replace(/^\\s+|\\s+$/g, "");
1003. },
1004. // 把参数array转换成数组。有可能是dom collection,arguments，jquery对象
1005. makeArray : function(array) {
1006. var ret = \[];
1007. **if** (array != **null**) {
1008. var i = array.length;
1009. // the window, strings and functions also have 'length'
1010. **if** (i == **null** || array.split || array.setInterval || array.call)
1011. ret\[0] = array;
1012. **else**
1013. **while** (i)
1014. ret\[--i] = array\[i];
1015. }
1016. **return** ret;
1017. },
1018. // 判断elem元素在array中的位置(index)
1019. inArray : function(elem, array) {
1020. **for** (var i = 0, length = array.length;i &lt; length; i++)
1021. // Use === because on IE, window == document
1022. **if** (array\[i] === elem)
1023. **return** i;
1024. **return** -1;
1025. },
1026. // 把second 元素追加到first的数组中。
1027. merge : function(first, second) {
1028. // We have to loop this way because IE & Opera overwrite the length
1029. // expando of getElementsByTagName
1030. var i = 0, elem, pos = first.length;
1031. // Also, we need to make sure that the correct elements are being
1032. // returned
1033. // (IE returns comment nodes in a '\*' query)
1034. **if** (jQuery.browser.msie) {
1035. **while** (elem = second\[i++])
1036. **if** (elem.nodeType != 8)
1037. first\[pos++] = elem;
1038. } **else**
1039. **while** (elem = second\[i++])
1040. first\[pos++] = elem;
1041. **return** first;
1042. },
1043. // 判断数组中的元素是否有重复的元素，返回不重复的所有元素。如Ext.DomQuery中的nodup一样处理
1044. unique : function(array) {
1045. var ret = \[], done = {};
1046. **try** {
1047. **for** (var i = 0, length = array.length;i &lt; length; i++) {
1048. var id = jQuery.data(array\[i]);
1049. **if** (!done\[id]) {
1050. done\[id] = **true**;
1051. ret.push(array\[i]);
1052. }
1053. }
1054. } **catch** (e) {
1055. ret = array;
1056. }
1057. **return** ret;
1058. },
1059. // 过滤elems中满足callback处理的所有元素
1060. grep : function(elems, callback, inv) {
1061. var ret = \[];
1062. // Go through the array, only saving the items
1063. // that pass the validator function
1064. **for** (var i = 0, length = elems.length;i &lt; length; i++)
1065. **if** (!inv != !callback(elems\[i], i))
1066. ret.push(elems\[i]);
1067. **return** ret;
1068. },
1069. // 返回对elems每个元素都进行操作的callback函数的返回值的集合。
1070. map : function(elems, callback) {
1071. var ret = \[];
1072. // Go through the array, translating each of the items to their
1073. // new value (or values).
1074. **for** (var i = 0, length = elems.length;i &lt; length; i++) {
1075. var value = callback(elems\[i], i);
1076. **if** (value != **null**)
1077. ret\[ret.length] = value;
1078. }
1079. **return** ret.concat.apply(\[], ret);
1080. }
1081. });
1082. var userAgent = navigator.userAgent.toLowerCase();
1083. // 计算出浏览器的相关信息
1084. jQuery.browser = {
1085. version : (userAgent.match(/.+(?:rv|it|ra|ie)\[\\/: ](\[\\d.]+)/) || \[0, '0'])\[1],
1086. safari : /webkit/.test(userAgent),
1087. opera : /opera/.test(userAgent),
1088. msie : /msie/.test(userAgent) && !/opera/.test(userAgent),
1089. mozilla : /mozilla/.test(userAgent)
1090. && !/(compatible|webkit)/.test(userAgent)
1091. };
1092. var styleFloat = jQuery.browser.msie ? "styleFloat" : "cssFloat";
1093. jQuery.extend( {
1094. // 支持不支持boxModel?IE不支持
1095. boxModel : !jQuery.browser.msie || document.compatMode == "CSS1Compat",
1096. props : {
1097. "for" : "htmlFor",
1098. "class" : "className",
1099. "float" : styleFloat,
1100. cssFloat : styleFloat,
1101. styleFloat : styleFloat,
1102. readonly : "readOnly",
1103. maxlength : "maxLength",
1104. cellspacing : "cellSpacing",
1105. rowspan : "rowSpan"
1106. }
1107. });
1108. // 一组对元素的相关节点的操作，如父，子，兄节点等
1109. jQuery.each( {
1110. parent : function(elem) {// 父亲节点
1111. **return** elem.parentNode;
1112. },
1113. parents : function(elem) {// elem的所有parentNode
1114. **return** jQuery.dir(elem, "parentNode");
1115. },
1116. next : function(elem) {// 元素的下一个兄弟
1117. **return** jQuery.nth(elem, 2, "nextSibling");
1118. },
1119. prev : function(elem) {// 前一个兄弟
1120. **return** jQuery.nth(elem, 2, "previousSibling");
1121. },
1122. nextAll : function(elem) {// 所有后继兄弟
1123. **return** jQuery.dir(elem, "nextSibling");
1124. },
1125. prevAll : function(elem) {// 所有前继兄弟
1126. **return** jQuery.dir(elem, "previousSibling");
1127. },
1128. siblings : function(elem) {// 所有兄弟
1129. **return** jQuery.sibling(elem.parentNode.firstChild, elem);
1130. },
1131. children : function(elem) {// 所有孩子
1132. **return** jQuery.sibling(elem.firstChild);
1133. },
1134. contents : function(elem) {// iframe?就是文档，或者所有子节点
1135. **return** jQuery.nodeName(elem, "iframe") ? elem.contentDocument
1136. || elem.contentWindow.document : jQuery
1137. .makeArray(elem.childNodes);
1138. }
1139. }, function(name, fn) {// 注册到jQuery对象中去，可以调用同名方法
1140. jQuery.fn\[name] = function(selector) {
1141. var ret = jQuery.map(**this**, fn);// 每个元素都执行同名方法
1142. **if** (selector && typeof selector == "string")
1143. ret = jQuery.multiFilter(selector, ret);// 过滤元素集
1144. **return** **this**.pushStack(jQuery.unique(ret));// 构建jQuery对象
1145. };
1146. });
1147. // 为jQuery对象生成appendTo~replaceAll五个代理函数
1148. // 其功能是把当前的jquery对象的每个元素都插入到每个传入的参数(元素）的一个位置：
1149. // 之前，之后，开始，结束,overwrite
1150. jQuery.each( {
1151. appendTo : "append",
1152. prependTo : "prepend",
1153. insertBefore : "before",
1154. insertAfter : "after",
1155. replaceAll : "replaceWith"
1156. }, function(name, original) {
1157. jQuery.fn\[name] = function() {
1158. var args = arguments;// 每个参数和每个元素是对应起来的
1159. // 对当前jQuery中每个元素都进行的操作
1160. **return** **this**.each(function() {
1161. **for** (var i = 0, length = args.length;i &lt; length; i++)
1162. jQuery(args\[i])\[original](**this**);// 调用original代理工作
1163. });
1164. };
1165. });
1166. // 一组对元素attr,class等进行操作的函数
1167. jQuery.each( {
1168. removeAttr : function(name) {// 除去元素的一个属性
1169. jQuery.attr(**this**, name, "");
1170. **if** (**this**.nodeType == 1)
1171. **this**.removeAttribute(name);
1172. },
1173. addClass : function(classNames) {// 为元素增加一些classNames
1174. jQuery.className.add(**this**, classNames);
1175. },
1176. removeClass : function(classNames) {// 除去元素的一些classNames
1177. jQuery.className.remove(**this**, classNames);
1178. },
1179. toggleClass : function(classNames) {// 开关该class，
1180. jQuery.className[jQuery.className.has(**this**, classNames)
1181. ? "remove"
1182. : "add"](**this**, classNames);
1183. },
1184. remove : function(selector) {// 根据selector除去元素，防内存泄露
1185. **if** (!selector || jQuery.filter(selector, \[**this**]).r.length) {
1186. // Prevent memory leaks
1187. jQuery("\*", **this**).add(\[**this**]).each(function() {
1188. jQuery.event.remove(**this**);
1189. jQuery.removeData(**this**);
1190. });
1191. **if** (**this**.parentNode)
1192. **this**.parentNode.removeChild(**this**);
1193. }
1194. },
1195. empty : function() {// 清除元素的所有子节点
1196. // 删除当前对象的每个元素的的所有子节点，防止内存泄漏
1197. jQuery("&gt;\*", **this**).remove();
1198. **while** (**this**.firstChild)
1199. // 删除余留的子节点
1200. **this**.removeChild(**this**.firstChild);
1201. }
1202. }, function(name, fn) {
1203. jQuery.fn\[name] = function() {
1204. **return** **this**.each(fn, arguments);
1205. };
1206. });
1207. // 为jQuery对象注册height,width方法
1208. jQuery
1209. .each(
1210. \["Height", "Width"],
1211. function(i, name) {
1212. var type = name.toLowerCase();
1213. jQuery.fn\[type] = function(size) {
1214. // window的宽度和高度
1215. **return** **this**\[0] == window ? (// window的宽度和高度
1216. jQuery.browser.opera
1217. && document.body\["client" + name]
1218. || jQuery.browser.safari
1219. && window\["inner" + name]
1220. || document.compatMode == "CSS1Compat"
1221. && document.documentElement["client"
1222. + name] || document.body["client"
1223. + name])
1224. : **this**\[0] == document ? (// document的宽度和高度
1225. Math
1226. .max(
1227. Math
1228. .max(
1229. document.body["scroll"
1230. + name],
1231. document.documentElement["scroll"
1232. + name]),
1233. Math
1234. .max(
1235. document.body["offset"
1236. + name],
1237. document.documentElement["offset"
1238. + name])))
1239. : (size == undefined ? (// 第一个元素的的宽度和高度
1240. **this**.length ? jQuery.css(
1241. **this**\[0], type) : **null**)
1242. : (// 设定当前对象所有元素宽度和高度
1243. **this**
1244. .css(
1245. type,
1246. size.constructor == String
1247. ? size
1248. : size
1249. + "px")));
1250. };
1251. });
1252. // Helper function used by the dimensions and offset modules
1253. function num(elem, prop) {
1254. **return** elem\[0] && parseInt(jQuery.curCSS(elem\[0], prop, **true**), 10) || 0;
1255. }