模仿jQuery each函数的链式调用
作者:bea
代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Each Document
代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Each Document</title>
<script type="text/javascript">
(function(){ //创建一个自执行函数
function _$(el){ //声明一个类
this.elements = []; //用于保存DOM元素的引用
for (var i = 0; i < el.length; i++) {
var element = el[i];
if (typeof element == string ) {
element = document.getElementById(element);
}
this.elements.push(element);
}
}
_$.prototype = {
each: function(fn){
for (var i = 0; i < this.elements.length; i++) {
fn.call(this, this.elements[i]); //第二个参数是fn函数的参数
}
},
setStyle: function(prop, val){
var that = this;
this.each(function(el){ //注意参数的设置
el.style[prop] = val;
});
return this;
}
}
window.$ = function(){
return new _$(arguments);
};
})();
window.onload = function(){
$("p", "p2").setStyle("color", "red");
}
</script>
</head>
<body>
<p id="p">
Hello world
</p>
<p id="p2">
Welcome.
</p>
</body>
</html>
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- javascript 动态table添加colspan owspan 参数的方法
- jquery 表单下所有元素的隐藏
- 运用jquery实现table单双行不同显示并能单行选中
- 用JQuery 实现AJAX加载XML并解析的脚本
- Prototype Selector对象学习
- Prototype 工具函数 学习
- 用js模仿word格式刷功能实现代码 [推荐]
- JQuery CSS样式控制 学习笔记
- JQuery 学习笔记 element属性控制
- JQuery 学习笔记 选择器之六
- JQuery 学习笔记 选择器之五
- JQuery 学习笔记 选择器之四
- JQuery 学习笔记 选择器之三
- JQuery 学习笔记 选择器之二
- JQuery 学习笔记 选择器之一
- javascript IFrame 强制刷新代码
- jQuery TextBox自动完成条
- JavaScript 动态生成方法的例子
- JavaScript 就地编辑HTML节点实现代码