二十多行代碼實(shí)現(xiàn)一個簡易 jQuery
- 先寫一個叫 jQuery 的構(gòu)造函數(shù),并且將它作為全局變量,方便調(diào)用,并且這個函數(shù)可以接受一個選擇器字符串用于選擇符合條件的元素,或直接接受一個節(jié)點(diǎn),最后返回一個偽數(shù)組的節(jié)點(diǎn)對象。
window.jQuery = function(nodeOrSelector) {
let nodes = {};
if (typeof nodeOrSelector === 'string') {
nodes = document.querySelectorAll(nodeOrSelector);
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
};
}
return nodes;
};
利用typeof操作符來判斷參數(shù)是否是字符串,若為true,則利用DOM的querySelectorAll獲取所有相關(guān)節(jié)點(diǎn),否則再用instanceof判斷參數(shù)是否為一個Node對象,若是則構(gòu)造一個長度為1的偽數(shù)組。
- 現(xiàn)在我們獲得了一個可供操作的偽數(shù)組對象
nodes了,但是還沒有提供用于操作它的方法。我們?yōu)樗帉憙蓚€方法addClass和setText,它們的邏輯都差不多,都是先接受一個參數(shù),然后利用for循環(huán)遍歷偽數(shù)組對象nodes,最后利用節(jié)點(diǎn)自帶的方法對每個節(jié)點(diǎn)進(jìn)行修改。
window.jQuery = function(nodeOrSelector) {
let nodes = {};
if (typeof nodeOrSelector === 'string') {
nodes = document.querySelectorAll(nodeOrSelector);
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
};
}
nodes.addClass = function(className) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(className);
}
};
nodes.setText = function(text) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
};
return nodes;
};
- 給它一個縮寫
$,讓它看起來更像jQuery
window.$ = jQuery;
- 這樣一個簡易的jQuery就實(shí)現(xiàn)了,現(xiàn)在可以試著使用它了
$('li').addClass('red'); //為所有l(wèi)i標(biāo)簽添加一個叫red的class
$('li').setText('Hello'); //將所有l(wèi)i標(biāo)簽的文本內(nèi)容改為Hello