實現代碼大概邏輯流程就是:node
1.首先提出問題:假設要給li元素添加class類演示和文本內容,該如何實現?數組
2.解決問題:bash
1.1首先得獲取到全部的元素,知道有幾個li元素須要進行調整,因此得使用循環遍從來找出全部的li元素。閉包
2.2.獲取到全部li元素後,要對每個li元素都添加class類樣式,一樣的也須要循環遍從來給每一個li元素添加樣式。函數
3.3要給每個li元素添加文本內容,一樣的也須要循環遍從來給每一個li元素添加內容。ui
4.4既然要作三件事,那就得用三個函數來實現。spa
邏輯對了,實現起來代碼就會更加的快捷和準確。設計
window.jQuery = function(nodeOrSelector){
let nodes ={}
if (typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)//僞數組
for(let i = 0;i<temp.length;i++){
nodes[i] = temp[i]
}
nodes.length = temp.length
}else if(nodeOrSelector instanceof Node){
nodes = {
0:nodeOrSelector,
length:1
}
}//循環遍歷出全部的nodeOrSelector,例如:li
nodes.addClass = function (classes){
classes.forEach(value) => {
for(let i = 0;i<nodes.length;i++){
nodes[i].classList.add(value)
}
}
}//給全部的li添加class類,
nodes.text = function(text){
if (text === undefined){
var texts =[]
for(let i = 0;i<nodes.length;i++){
texts.push(nodes[i].textContent)
}
return texts
}else{
for(let i = 0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
}//給全部的li添加‘hi’
return nodes
}
window.$ = jQuery
$li = $('ul>li')
$li.addClass(['blue'])
$li.text('hi')
複製代碼
以上是一個利用原生js封裝成函數後來講明jQuery內部運行的基本原理,咱們能夠模仿jQuery隨意添加元素節點和類來進行頁面內容的控制,可讓咱們對jQuery有個更清楚的瞭解, 由於在理解過程當中有一些代碼讓我困擾了一會,爲了加深理解,特進行單獨的說明,code
nodeOrSelector instanceNode
這段代碼我當時也是很不理解,由於通常instanceof是用來檢測對象類型的,而這個Node看上去也不是我所瞭解的對象類型,instanceof通常使用方法以下:對象
alert(person instanceof Object); // 變量 person 是 Object 嗎?
alert(colors instanceof Array); // 變量 colors 是 Array 嗎?
alert(pattern instanceof RegExp); // 變量 pattern 是 RegExp 嗎?
複製代碼
Node好像不在這些引用類型當中呀!《js高程設計》中也沒有說,通常Node好像是做爲節點來用,o(╥﹏╥)o 而後我翻了翻網上的文檔,最後明白了,這個Node是做爲Node對象,Node對象是屬於DOM裏面的對象,而Object,Array,Date,RegExp,Function等是屬於ECMAscript裏面的對象,所以他們均可以使用這個instanceof來檢測對象類型,理解了這個,也就茅塞頓開了。
在上面的代碼中,咱們也是用了閉包:
nodes.addClass = function (classes){xxx}
nodes.text = function(text){}
上面這倆函數都訪問了他們外部的變量nodes,從而能夠進行class類的添加和textcontent文本內容的添加,這裏就是使用閉包函數的好處,
4.後面在遇到關於jQuery和DOM有關的問題將在後面繼續補充,