jQuery笔记

自己封装两个函数

1.获取传入节点的所有兄弟,,结果返回一个对象

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

2.对节点添加或删除class

function addClass(node,classes) {
    for(var key in classes) {
        var value = classes[key];
        if(value){
            node.classList.add(key);
        }else {
            node.classList.remove(key);
        }
    }
}

3.代码优化

node.classList.add(key);
node.classList.remove(key);
这两句代码类似,可以改成这样:
var methodName = classes[key] ? "add" : "remove";

命名空间

将一个对象封装好函数,设置到全局对象window当中,这就是所谓的命名空间。代码如下:

window.yyDom = {};
yyDom.getSiblings = function(node){}
yyDom.addClass = function(node,classes){}
// 调用时我们只需要按照如下调用即可:
    console.log(yyDom.getSiblings(item3));
    yyDom.addClass(item3,{a:true});

能不能把 node 放在前面

使用Node.prototype

 Node.prototype.getSiblings = function(){
        var allChildren = this.parentNode.children;
        var array = {
            length:0
        }
        for(var i=0;i

简易的jQuery

window.jQuery = function(nodeOrSelector){
  let nodes = { }
    if (typeof nodeOrSelector === 'string') {
          let temp = []
          temp = document.querySelectorAll(nodeOrSelector)
          temp.forEach((node, index) => {
              nodes[index] = node
          })
          nodes.length = temp.length
    }
    else if (nodeOrSelector instanceof Node) {
        nodes = {0: nodeOrSelector, length: 1}
    }
  
  
   nodes.addClass = function (classes) {
            classes.forEach(function (value) {
                for (let i = 0; i < nodes.length; i++) {
                    nodes[i].classList.add(value)
                }
            })
        }

        nodes.setText = function(text){
      for(let i =0;i < nodes.length;i++){
        nodes[i].textContent = text
    }
  }
  
  return nodes
};
var node = jQuery('ul>li');
    console.log(node.text());
    node.text.call(node,'hi');
    node.addClass.call(node,{'red':true});

你可能感兴趣的:(jQuery笔记)