自我封裝jQuery代碼
window.jQuery = function(nodeOrSelector) {
let nodes = {}
if (typeof nodeOrSelector === 'string') {
let tmp = document.querySelectorAll(nodeOrSelector);
for(var i =0; i < tmp.length; i++){
nodes[i] = tmp[i];
}
nodes.length = i;
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
}
}
nodes.addClass = function(classs) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(classs);
}
}
nodes.setText = function(text){
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
}
return nodes;
}
window.$ = jQuery
var $div = $('div')
$div.addClass('red') // 可將所有 div 的 class 添加一個 red
$div.setText('222') // 可將所有 div 的 textContent 變?yōu)?hi
代碼實現(xiàn)過程
window.jQuery = function(nodeOrSelector)
- 一般我們的得到的元素都是一個dom對象,而這個對象最終繼承的就是Node接口
- 所以可以在 Node.prototype 上添加以上 addClass 及setText 方法
- 但是Node.prototype 是一個共有對象,每個人寫的程序都不一樣絮供, 如果大家都在這里面操作添加刪除API , 就會出現(xiàn)各種問題
- 所以我們可以取一個我們自己喜歡的名字來當(dāng)作我們簡便操作dom樹似舵,這個構(gòu)造函數(shù)就不會被別人亂修改啦劝枣,而jQuery的作者就取名叫jQuery的
- 為了更懶更簡便的操作男韧,所以讓$ = jQuery
let nodes = {}
if (typeof nodeOrSelector === 'string') {
let tmp = document.querySelectorAll(nodeOrSelector);
for(var i =0; i < tmp.length; i++){
nodes[i] = tmp[i];
}
nodes.length = i;
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
}
}
- 因為jQuery 傳入的有可能是字符串形式的選擇器 或者 節(jié)點元素氢哮,所以 這段代碼實現(xiàn)的功能是
- 先創(chuàng)建一個對象
- 判斷傳入的參數(shù)是字符串還是dom對象
- 如果是字符串就document.querySelectorAll匹配所有符合的選擇器的元素,然后改成jQuery形式的對象诬烹,也就是我們開始創(chuàng)建的對象砸烦,不能直接復(fù)制給這個對象,因為匹配得到的對象是NodeList對象绞吁,是dom類型對象
- 如果是節(jié)點元素就直接添加進(jìn)第一項就好了
- 因為jQuery ,$div[0] === div
nodes.addClass = function(classs) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(classs);
}
}
nodes.setText = function(text){
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
}
return nodes;
- 最后就是給這個要返回的對象添加API啦
- 真正的jQuery的API都是封裝在jQuery.prototype中幢痘,所有的jQuery對象都共用這些API
- 這里的nodes就與兩個方法之間產(chǎn)生了閉包, 保護(hù)了nodes的私有化
window.$ = jQuery
var $div = $('div')
$div.addClass('red') // 可將所有 div 的 class 添加一個 red
$div.setText('222') // 可將所有 div 的 textContent 變?yōu)?hi
- 為了更方便的操作 用
$
代替jQuery 家破,var $div = $('div')
可以 var $div = jQuery('div')
也是一樣的
- 構(gòu)造函數(shù)返回的對象就包含了兩個方法颜说, 我們就可以直接調(diào)用啦,