詳解jquery選擇器的原理
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。
以上就是jQuery 原理的分析,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!