您的位置:首页 > Web前端 > JQuery

jquery选择器的实现原理

2016-11-03 00:57 381 查看
html部分
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="js/minijquery.js"></script>
</head>
<body>
<div class="one">1</div>
<div class="two">2</div>
</body>
<script>
var result = $("div");
console.log(result);
alert($('div').size());
</script>
</html> js

js部分

(function(){
//暴露外部的引用
var jQuery = window.jQuery = window.$ = function(selector){
return new jQuery.fn.init(selector);
}

//添加原型事件
jQuery.fn = jQuery.prototype = {
//
init:function(selector){
var element = document.getElementsByTagName(selector);
Array.prototype.push.apply(this,element);
return this;
},
myjQuery:"the test one",
length:0,
size:function(){
return this.length;
}
}

//将init的原型引用成jQuery的原型
jQuery.fn.init.prototype = jQuery.fn;

})();
我用我的理解解释一下,就是jquery原型里面有一个init初始化的方法,将传入的值进行解析,比如传入的id还是class还是标签名。然后通过相应的方法返回数组型对象。既可以通过对象直接调用方法,也可以使用数组的length。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: