實現(xiàn)一個 jQuery 的 API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>實現(xiàn)一個 jQuery 的 API</title>
    <style>
        .blue{
        color: blue;
        }
    </style>
</head>
<body>
    <ul>
        <li>項目1</li>
        <li>項目2</li>
        <li>項目3</li>
        <li>項目4</li>
        <li>項目5</li>
      </ul>
    <script>
        window.jQuery = function(nodeOrSelector){ // 傳入的參數(shù)是字符串或者節(jié)點
            let nodes = {} // 偽數(shù)組nodes 保存選擇器對應(yīng)的一個或多個節(jié)點
            if(typeof nodeOrSelector === 'string'){     
                let temp = document.querySelectorAll(nodeOrSelector)//返回nodeList偽數(shù)組
                for(let i=0; i<temp.length; i++){ // 不想要多余的原型鏈,nodes原型鏈直接指向Object
                    nodes[i] = temp[i]
                }
                nodes.length = temp.length
                }else if(nodeOrSelector instanceof Node){
                    nodes = {
                        0: nodeOrSelector,
                        length: 1
                    }
            }
            nodes.addClass = function(classes){ //在nodes對象(哈希)加addClass屬性
                classes.forEach((value) => { //添加所有class
                    for(let i=0; i<nodes.length; i++){// 遍歷所有節(jié)點,即所有節(jié)點都添加該class
                        nodes[i].classList.add(value)
                    }
                })
            }
            nodes.text = function(text){ //在nodes對象(哈希)加text屬性
                if(text === undefined){ // 不給參數(shù)就是獲取
                    var texts = []
                    for(let i=0; i<nodes.length; i++){
                    texts.push(nodes[i].textContent)
                    }
                    return texts
                }else{ // 給參數(shù)就是設(shè)置
                    for(let i=0; i<nodes.length; i++){
                        nodes[i].textContent = text
                    }
                }
            }
            return nodes // 返回給node2
        }
        
        window.$ = jQuery
        var $node2 = $('ul > li') // node2等于jQuery函數(shù)返回值(純凈的偽數(shù)組nodes),為了區(qū)分,jQuery的變量前加$
        $node2.addClass(['blue','a','b','c']) // 可添加多個class名
        $node2.text('hi')
        console.log($node2)
        console.log($node2.text()) //不給參數(shù)就是獲取 textContent
    </script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容