我的''jQuery''和jQuery

Pomelo1213發表於2018-01-22

寫在最前面:對jQuery的初步認識,以及自己對jQuery的摸索。

首先實現我需要的函式


function getSiblings(node){}
和
function addClass(node, classes){}
複製程式碼

如下:

function getSiblings(node){
    var allNodes = node.parentNode.children;
    var array = {length: 0};
    for(let i= 0; i < allNodes.length; i++){
        if(allNodes[i] !== node){
            array[array.length] = allNodes[i]
            length++;
        }
    }
    return array;
}

function addClass(node, classes){
    classes.forEach( (value) => node.classList.add(value) )
}
複製程式碼

嘗試再給加上名稱空間:


var dom = {
    getSiblings: function getSiblings(node){...}
    addClass: function addClass(node, classes){...}
}
複製程式碼

再考慮下能不能做的更直觀一些:


我們可以試著將其放到Node介面上(Node.prototype)

Node.prototype.getSiblings = function (){...}
Node.prototype.addClass = function(classes){...}
複製程式碼

例如:item.getSiblings();

這樣一來我們可以直接用元素來直接使用。但是也會帶來一些問題:例如全域性汙染、出了Bug不容易定位問題以及會與其他引入的庫造成衝突。所以一般來說,我們不應該直接在原型上新增方法。

Another way


使用我們自己的介面來封裝例如‘jQuery’

function jQuery(node){
    return {
        element: node,
        getSiblings: function(){},
        addClass: function(classes){}
    }
}
複製程式碼

這樣一來,我們可以輕鬆的使用方法,並且不再擔心對後續的影響,如果再來一個alisa就更完美了!window.$ = jQuery:

var x = document.getElementById('x');
var $myNode = $(x)
$myNode.getSiblings();
$myNode.addClass('color');
複製程式碼

完整程式碼(新增了text方法)

window.jQuery = function(nodeOrSelector){
    var nodes = {};
    if(nodeOrSelector === 'string'){
        let things = document.querySelectorAll(nodeOrSelector);
        for(let i = 0; i< things.length; i++){
            nodes[i] = things[i];
        }
        nodes.length = things.length;
    }else if(nodeOrSelector instanceof Node){
        nodes = {0: nodeOrSelector, length: 1}
    }
    
    nodes.getSiblings = function(){
        let allNodes = nodes.parentNode.children;
        let array = {length: 0}
        for(let i = 0; i < allNodes.length; i++){
            if(allNodes !== nodes){
                array[array.length] = allNodes[i];
                length++;
            }
        }
        return array;
    }
    
    nodes.addClass = function(classes){
        classes.forEach(value => {
            for(let i = 0; i < nodes.length; i++)
               nodes[i].classList.add(value); 
        }
        })
    }
    
    nodes.getText = function(){
        let text = [];
        for(let i = 0; i < nodes.length; i++){
            text.push(nodes[i].textContent);
        }
        return text;
    }
    
    nodes.setText = function(text){
        for(let i = 0; i < nodes.length; i++){
            nodes[i].textContent = text;
        }
    }
    
    return nodes;
}
複製程式碼

到這裡算是模仿了jQuery是如何讓人們方便的使用它。

相關文章