zl程序教程

您现在的位置是:首页 >  其它

当前栏目

模仿jQueryeach函数的链式调用

函数 调用 模仿 链式 jqueryeach
2023-06-13 09:14:11 时间
复制代码代码如下:

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=iso-8859-1">
<title>EachDocument</title>
<scripttype="text/javascript">
(function(){//创建一个自执行函数
function_$(el){//声明一个类
this.elements=[];//用于保存DOM元素的引用
for(vari=0;i<el.length;i++){
varelement=el[i];
if(typeofelement==string){
element=document.getElementById(element);
}
this.elements.push(element);
}
}

_$.prototype={
each:function(fn){
for(vari=0;i<this.elements.length;i++){
fn.call(this,this.elements[i]);//第二个参数是fn函数的参数
}
},
setStyle:function(prop,val){
varthat=this;
this.each(function(el){//注意参数的设置
el.style[prop]=val;
});
returnthis;
}
}

window.$=function(){
returnnew_$(arguments);
};
})();

window.onload=function(){
$("p","p2").setStyle("color","red");
}
</script>
</head>
<body>
<pid="p">
Helloworld
</p>
<pid="p2">
Welcome.
</p>
</body>
</html>