實現相似jQuery庫中的兩個方法

window.jQuery = function (node) {
            let obj = {
                length: 0
            }
            if (typeof node === 'string') {
                let getAllnodes = document.querySelectorAll(node)
                for (let j = 0; j < getAllnodes.length; j++) {
                    obj[j] = getAllnodes[j]
                }
                obj.length = getAllnodes.length

            } else if (node instanceof Node) {
                //這裏若是node是Node的實例說明只獲取到一個元素
                obj[0] = node
                obj.length = 1
            } else if (length in node && node[0] instanceof Node) {
                for (let j = 0; j < node.length; j++) {
                    obj[j] = node[j]
                }
                obj.length = node.length
            } else {
                return '出錯,請檢查你所傳入的元素是否正確'
            }

            obj.addClass = function (classes) {
                let classNames = classes.split(' ')
                classNames.forEach(className => {
                    for (let j=0;j<obj.length;j++) {
                        obj[j].classList.add(className)
                    }
                })
            }
            obj.setText = function (text) {
                for (let j=0;j<obj.length;j++) {
                    obj[j].textContent = text
                }
            }
            return obj
        }
        window.$ = jQuery
        let $div = $('li')
        $div.addClass('red green')
        $div.setText('hi')
複製代碼
相關文章
相關標籤/搜索