模拟jquery的$()选择器的实现

<html>
<head>
</head>
<body>
<div id="div1">div1</div>

<div class=".div2">aaaa</div>
<div class=".div2">aaaa</div>

<p>p1</p>
<p>p2</p>

<script>

var TQObject = function(){
	this.data=[];
}

TQObject.prototype = {}

var $=function(selecter)
{
	this.tqOjbect = new TQObject();
	if (selecter.substring(0,1) == "#") {
		var elem = document.getElementById(selecter.substring(1));
		this.tqOjbect.data.push(elem);
	} else if (selecter.substring(0,1) == ".") {
		var elems = document.getElementsByTagName("*");
		console.log(elems);
		var reg  = new RegExp("(^|\\s)" + selecter.substring(1) + "($|\\s)");
		console.log(reg);
		for (var i=0;i<elems.length;i++) {
			if (reg.test(elems[i].className.substring(1))) {
				this.tqOjbect.data.push(elems[i]);
			}
		}
	} else {
		var elems = document.getElementsByTagName(selecter);
		this.tqOjbect.data.push(elems);
	}
	return tqOjbect;
}

window.onload=function(){
	var ele1 = $("#div1");
	var ele2 = $(".div2");
	var ele3 = $("p");

	console.log(ele2);
}
</script>
</body>
</html>

  

posted @ 2016-12-13 18:41  风与叶子  阅读(2270)  评论(0编辑  收藏  举报