今天開始學習jQuery,理解其實現模式和大體思想,然后自己簡單實現一些類jQuery功能,這樣能更好地學習使用它。直接看代碼,實現細節將以注釋形式講解。
window.jQuery = function (nodeOrSelector) { // 添加全局函數,返回一個偽數組(hash)
var nodes = {};
if (typeof nodeOrSelector === 'string') {
// 檢測傳入類型,如果是字符串則是一個css選擇器,遂使用querySelectorAll
var temp = document.querySelectorAll(nodeOrSelector); // 返回偽數組
for (let i = 0; i < temp.length; i++) {
// 遍歷偽數組并將其加入nodes,添加length屬性
nodes[i] = temp[i];
nodes.length = temp.length;
}
} else if (nodeOrSelector instanceof Node) {
// 檢測是否是一個元素節點 ,同樣將其組織成偽數組形式
nodes = {
0: nodeOrSelector,
length: 1
}
}
// 為nodes添加方法,這樣在返回nodes后就可以直接使用nodes.xxx的形式調用方法
nodes.addClass = function (c) {
for (let i = 0; i < nodes.length; i++) {
// 遍歷nodes,為其中的每個元素添加class
nodes[i].classList.add(c);
}
}
nodes.setText = function (text) {
// 設置文本,改變元素的顯示文本,同樣使用遍歷的方法
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
}
return nodes;
}
window.$ = jQuery; // 將jQuery改名為$,方便調用
以上是jQuery實現的大體形式,這只是一個極簡版,主要在于體會其設計思想,真正的jQuery實現過程自然是要復雜的多。