對于網(wǎng)頁開發(fā)者來說,學(xué)會jQuery是必要的。
jQuery的基本設(shè)計思想和主要用法,就是"選擇某個網(wǎng)頁元素,然后對其進(jìn)行某種操作"。這是它區(qū)別于其他Javascript庫的根本特點(diǎn)。
下面,我們自己寫一個構(gòu)造函數(shù),接收一個節(jié)點(diǎn),返回一個新的節(jié)點(diǎn)對象,同時我們可以使用新節(jié)點(diǎn)的API去做一些事情。
- 我們先寫一個構(gòu)造函數(shù),用于接收一個節(jié)點(diǎn),并判斷傳進(jìn)來的參數(shù)是字符串還是節(jié)點(diǎn)。
window.jQuery = function(nodeOrSelector){
let nodes = {}
if(typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)//偽數(shù)組
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
}
}
return nodes
}
- 我們給這個構(gòu)造函數(shù)添加兩個屬性:addClass(className) 和 setText(text)
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
}
}
最終,我們的構(gòu)造函數(shù)如下:
window.jQuery = function(nodeOrSelector){
let nodes = {}
if(typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)//偽數(shù)組
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
}
}
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
}