当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Jquery选择器 $实现原理

Javascript
有趣的script标签用getAttribute方法来自脚本吧
学习YUI.Ext 第二天
学习YUI.Ext 第三天
学习YUI.Ext第五日--做拖放Darg&Drop
学习YUI.Ext 第六天--关于树TreePanel(Part 1)
学习YUI.Ext 第七天--关于View&JSONView
学习YUI.Ext 第六天--关于树TreePanel(Part 2异步获取节点)
对YUI扩展的Gird组件 Part-2
Gird事件机制初级读本
为Yahoo! UI Extensions Grid增加内置的可编辑器
如何简单地用YUI做JavaScript动画
(function(){})()的用法与优点
JS层移支示例代码
如何在Web页面上直接打开、编辑、创建Office文档
网页中实现浏览器的最大,最小化和关闭按钮
[原创]js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结
图片自动缩小的js代码,用以防止图片撑破页面
收藏一些不常用,但是有用的代码
解决 firefox 不支持 document.all的方法
用ajax实现的自动投票的代码

Javascript 中的 Jquery选择器 $实现原理


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 332 ::
收藏到网摘: n/a

在此之前对于Microsoft Ajax的Sys和Jquery的$符号一直很好奇, 不明白为什么输入一个'$()'就可以实现选择器? 但由于工作的原因,很久不曾做过网站项目了,也没有时间去好好研究Jquery的源码,这个疑问也一直没有得到解决了, 今天,空闲之余,打开Jquery的源码看看,才明天它实现的原理,原来在加入jquery的js这个文件时,实际上是执行了一个函数,在这个函数里己经初始化了$和JQuery变量, 实现这个功能源码如下(代码已删减和更改,并不影响说明实现原理):
复制代码 代码如下:

(function() {
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context);
},
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/;
jQuery.fn = jQuery.prototype = {
init: function(selector, context) {
// Make sure that a selection was provided
// Make sure that a selection was provided
selector = selector || document;
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
},
show:function() {
alert("this.show");
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.3.2"
};
jQuery.fn.init.prototype = jQuery.fn;
})();
function test(src){
alert($(src));
$(src).show();

从代码里我们可以看到有这样一个函数执行了(funtion(){})();
var window = this;
_jQuery = window.jQuery;
_$ = window.$;
这几句代码应该是声明jQuery和$变量,至于为什么能这样子用我还没弄明白,等待高人解决!!
但我认为这并没关系,因为最重要的是下面这段代码:
jQuery = window.jQuery = window.$ = function(selector, context) {
return new jQuery.fn.init(selector, context);
};
可以看出创建jQuery.fn.init这样一个函数返回给$, 这样是可以使用$实例了,但还不能访问jQuery.fn里的方法,因此需要加上后面这句:
jQuery.fn.init.prototype = jQuery.fn;
实现了这些, Jquery中的其他功能就很好理解了, 无非是添prototype或extend中的方法了.