在jQuery源码的init里面有一段:
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
请问这个是做什么的?为什么要循环调用属性啊?
好吧~这个问题解决了~jQuery初始化方法还有一种方式,我平时没有使用过:
$("<div></div>", {width: "123", class: "123 1234", click: fun})
这样就循环把width,class通过attr添加到属性上,由于jquery对象有click方法,那么就会调用$().click(fun)来写入事件