代碼
window.jQuery=function(nodeOrSelector){
let nodes=[]
if(nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeSelector)
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(classes){
classes.forEach((value)=>{
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(value)
}
})
}
nodes.setText=function(text){
for(let i=0;i<nodes.lenght;i++)
{
nodes[i].textContent=text
}
}
return nodes
}
獲取dom節(jié)點
1.要判斷傳入的是字符串還是節(jié)點
2.最后要封裝成一個偽數(shù)組
編寫addClass方法
1.forEach方法遍歷傳入的參數(shù)數(shù)組
2.遍歷第一步的偽數(shù)組躯护,用dom api給數(shù)組中節(jié)點添加類
3.把該方法添加到偽數(shù)組中(node.addClass=function...)
編寫setText方法
1.遍歷第一步的偽數(shù)組览效,用dom api提供的textContent更新數(shù)組節(jié)點的文本
3.把該方法添加到偽數(shù)組中(node.setText=function...)
注意
window.$ = jQuery
var $div = $('div')
用jQ取值并賦值給變量時給變量前面加$
instanceof
instanceof運算符用于測試構(gòu)造函數(shù)的prototype屬性是否出現(xiàn)在對象的原型鏈中的任何位置
- 事例
function C(){}
function D(){}
var o = new C();
o instanceof C; // true概页,因為 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false言津,因為 D.prototype不在o的原型鏈上