代码改变世界

(十一)jQuery.extend代码段

2012-02-12 16:10  kwjlk  阅读(283)  评论(0编辑  收藏  举报

在jQuery.init();代码之后有一段jQuery.extend代码。这一段属于对jQuery基本功能的扩展。代码如下:

jQuery.init();jQuery.fn.extend({
// We're overriding the old toggle function, so
// remember it for later
_toggle: jQuery.fn.toggle,
toggle: function(a,b) {
// If two functions are passed in, we're
// toggling on a click
return a && b && a.constructor == Function && b.constructor == Function ? this.click(function(e){
// Figure out which function to execute
this.last = this.last == a ? b : a;

// Make sure that clicks stop
e.preventDefault();

// and execute the function
return this.last.apply( this, [e] ) || false;
}) :

// Otherwise, execute the old toggle function
this._toggle.apply( this, arguments );
},
hover: function(f,g) {

// A private function for haandling mouse 'hovering'
function handleHover(e) {
// Check if mouse(over|out) are still within the same parent element
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;

// Traverse up the tree
while ( p && p != this ) p = p.parentNode;

// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;

// Execute the right function
return (e.type == "mouseover" ? f : g).apply(this, [e]);
}

// Bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
},
ready: function(f) {
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
f.apply( document );

// Otherwise, remember the function for later
else {
// Add the function to the wait list
jQuery.readyList.push( f );
}

return this;
}
});

最后面ready函数是添加对页面加载完成函数的代码。如果页面已经加载则立即调用当前设置的监听函数,没有则将当前方法加入到ready事件的监听列表中。

返回头从第一个函数定义开始看。第一个函数toggle,通过之前对_toggle的注释中认为这个toggle对原先定义的toggle函数进行了重定义。看代码实现是扩展了原有toggle函数的功能。那么,原先toggle函数是实现了什么功能,这里又添加了什么功能的支持呢?通过观察嗲吗我们可以看到,这里的toggle函数对_toggle原有功能扩充代码即为return 这一行的代码。

第二个hover函数,其上的handleHover是响应mouseover和mouseout的方法。注意其实现中的

while ( p && p != this ) p = p.parentNode;

这一段代码,这段代码实现了当鼠标停留在元素内部的元素上时,依旧当作停留在当前元素上的处理。

分析完这一段代码,jQuery的基本功能算是已经完备了。剩下后面的代码是对jQuery进行的功能扩充(基本特效代码和Ajax功能支持),这些代码可以看作如何对jQuery进行功能扩展的学习。现在看完了jQuery的基本功能,思考一下学到的东西。

  • jQuery对CSS类和属性的操作
  • jQuery强大的DOM选择器
  • jQuery如果判断浏览器版本,和浏览器当前使用的盒子模型。
  • jQuery跨浏览器页面加载完成事件的监听。
  • jQuery的事件模型
  • jQuery extend、each的实现