码迷,mamicode.com
首页 > Web开发 > 详细

js链式操作DOM节点的简单封装

时间:2016-04-25 00:29:38      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

function Base() {
		//把返回的节点对象保存到一个Base 对象的属性数组里
		this.elements = [];
		//获取id 节点
		this.getId = function (id) {
			this.elements.push(document.getElementById(id));
			return this;
		};
		//获取name 节点数组
		this.getName = function (name) {
			var names = document.getElementsByName(name);
			for (var i = 0; i < names.length; i ++) {
			this.elements.push(targs[i]);
			}
			return this;
		}
		//获取元素节点数组
		this.getTagName = function (tag) {
			var tags = document.getElementsByTagName(tag);
			for (var i = 0; i < tags.length; i ++) {
			this.elements.push(tags);
			}
			return this;
		};
}

Base.prototype.click = function (fn) {
	for (var i = 0; i < this.elements.length; i ++) {
	this.elements[i].onclick = fn;
	}
	return this;
};
Base.prototype.css = function (attr, value) {
	for (var i = 0; i < this.elements.length; i ++) {
	this.elements[i].style[attr] = value;
	}
	return this;
}
Base.prototype.html = function (str) {
	for (var i = 0; i < this.elements.length; i ++) {
	this.elements[i].innerHTML = str;
	}
	return this;
}

var $ = function () {
    return new Base();
};

//调用 方法:$().getTagName("p").css("backgroundColor","red").html("title-----").click(function(){alert(1)})

 

js链式操作DOM节点的简单封装

标签:

原文地址:http://www.cnblogs.com/fangxuele/p/5428998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!