實現(xiàn)一個jQuery的API
主要實現(xiàn)以下的功能
- 給元素增加
class - 給對應(yīng)的元素設(shè)置文本
實現(xiàn)過程
- 首先聲明一個函數(shù)jQuery()封裝要實現(xiàn)上面功能的函數(shù)
- 在jQuery()函數(shù)中聲明一個對象nodes,這個對象中有兩個函數(shù),這兩個函數(shù)分別是實現(xiàn)上面的兩個功能
- 當(dāng)調(diào)用函數(shù)jQuery()的時候,在函數(shù)中判斷傳遞的參數(shù)是字符串還是節(jié)點,然后對不同的數(shù)據(jù)類型做出不同的處理
- 接著就是在對象nodes中用不同的函數(shù)實現(xiàn)不同的功能
- 然后jQuery()函數(shù)會返回對象nodes,從而可以在函數(shù)外面調(diào)用函數(shù)里面的對象中的方法
實現(xiàn)代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div>選項1</div>
<div>選項2</div>
<div>選項3</div>
<div>選項4</div>
<div>選項5</div>
<script>
window.jQuery=function(nodeOrSelector){
let nodes={}
let node1=[]
if(typeof nodeOrSelector==='string'){
let temp=document.querySelectorAll(nodeOrSelector)
for(let i=0;i<temp.length;i++){
node1[i]=temp[i]
}
// node1.length=temp.length
}else if(nodeOrSelector instanceof Node){
node1={
0:nodeOrSelector,
length:1
}
}
nodes.addClass=function(classes){
classes.forEach(value => {
for(let i=0;i<node1.length;i++){
node1[i].classList.add(value)
}
})
// console.log(Array.isArray(node1))
}
nodes.setText=function(text){
for(let i=0;i<node1.length;i++){
node1[i].textContent=text
}
}
return nodes
}
window.$=jQuery
var $div=$('div')
$div.addClass(['red'])
$div.setText('hi')
</script>
</body>
</html>