一、什么是链式?
$('div').click(function () {
$(this).find(".b").addClass("css");
})
上面代码实现的是在点击div后,找到div内的类名为class的dom节点,给他们添加名为css的class。
二、jQuery怎么实现的链式?
上源码:
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,i = 0;
if ( isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
classes = classesToArray( value );
if ( classes.length ) {
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
精髓就在addClass函数的最后的一句:return this ,只要让每个函数return this,把对象再返回回来,这样其他函数就可以立即被调用啦。
三、优点
- 节约JS代码,使代码看起来更优雅
- 返回的都是同一个对象,可以提高代码的效率
四、怎么在jQuery库上加函数?
<!DOCTYPE html>
<html>
<head>
<title>myJQ</title>
</head>
<body>
<button id="child1">1</button>
<button id="child2">2</button>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
$('#child1').click(function () {
$(this).hide();
})
$('#child2').click(function () {
$(this).myFn().hide();
})
}
)
//jQuery可以换成$,prototype可以换成fn
jQuery.prototype.myFn = function () {
console.log("我自己定义的");
return this;
}
console.log(jQuery.prototype.myFn);
</script>
</html>
上面的代码实现的是在jQuery的原型上定义自己需要的函数,然后通过return this就可以像jQuery一样实现链式调用!