评论

收藏

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

开发技术 开发技术 发布于:2021-07-27 11:06 | 阅读数:347 | 评论:0

<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>


关注下面的标签,发现更多相似文章