自己寫一個jquery
阿新 • • 發佈:2018-06-05
模擬 bubuko elements ret TE nts select IT tex
通過閱讀jquery原代碼, 我們可以模擬寫一個簡單的jquery
比如常用的
jQuery("div").css("color","red");
jQuery("#span1").css("color","green");
1. jQuery(), 因為是鏈式調用, 所以返回是一個對象。
jQuery = function(selector){ return new jQuery.prototype.init(selector); } jQuery.prototype = { constructor:jQuery, init:function(selector){ this.elements = document.querySelectorAll(selector); }, css:function(key, value){ ...... } }
此時,this.elements為所有合條件的html elements
2. css(), 對所有合適條件的element設置樣式。
css:function(key, value){ this.elements.forEach(element => { element.style[key] = value; }); }
3. 此時,css是訪問不了this.elements的。 因為this.elements是在init定義,並且init是構造函數。所以this.elements是init實例裏面的屬性。
jQuery.prototype.init.prototype=jQuery.prototype;
這樣 css()就能訪問this.elements.
完整代碼
jQuery = function(selector){ return new jQuery.prototype.init(selector); } jQuery.prototype = { constructor:jQuery, init:function(selector){ this.elements = document.querySelectorAll(selector); }, css:function(key, value){ this.elements.forEach(element => { element.style[key] = value; }); } } jQuery.prototype.init.prototype=jQuery.prototype;
最後起個別名
jQuery.fn=jQuery.prototype
jQuery = function(selector){ return new jQuery.fn.init(selector); } jQuery.fn = jQuery.prototype = { constructor:jQuery, init:function(selector){ this.elements = document.querySelectorAll(selector); }, css:function(key, value){ this.elements.forEach(element => { element.style[key] = value; }); } } jQuery.fn.init.prototype=jQuery.fn;
測試一下。
<html lang="en"> <head> <title>My jquery</title> </head> <body> <div> div 1 </div> <div> div 2 </div> <span id="span1"> span 1 </span> </body> <script type="text/javascript"> jQuery = function(selector){ return new jQuery.fn.init(selector); } jQuery.fn = jQuery.prototype = { constructor:jQuery, init:function(selector){ this.elements = document.querySelectorAll(selector); }, css:function(key, value){ this.elements.forEach(element => { element.style[key] = value; }); } } jQuery.fn.init.prototype=jQuery.fn; jQuery("div").css("color","red"); jQuery("#span1").css("color","green"); </script> </html>
自己寫一個jquery