美文网首页
2019-03-24 jQuery

2019-03-24 jQuery

作者: 追夢的蚂蚁 | 来源:发表于2019-03-26 00:07 被阅读0次
用===,不要用==
  1. 自己封装两个函数
    function getSiblings(node){}
function getSiblings(node) {
            var allChildren = node.parentNode.children
            var array = {
                length: 0
            }
            for (let i = 0; i < allChildren.length; i++) {
                if (allChildren[i] !== node) {
                    array[array.length] = allChildren[i]
                    array.length += 1
                }
            }
            return array
        }
        console.log(getSiblings(item3))

再封装一个
function addClass(node, classes){}

function addClass(node,classes){
for(let key in classes){
  var value = classes[key]
  if(value){
    node.classList.add(key)
  }else{
    node.classList.remove(key)
  }
}
}
addClass(item3,{a:true,b:false,c:true})
  1. 命名空间
    window.ffdom={}
    ffdom.getSiblings = getSiblings
    ffdon.addClass = addClass

ffdom.getSiblings(item3)
ffdom.addClass(item3,['a','b','c'])

  1. Node.prototype
Node.prototype.getSiblings = function(){
  var allChildren = this.parentNode.children

  var array = {
    length: 0
  }
  for (let i = 0; i < allChildren.length; i++) {
    if (allChildren[i] !== this) {
      array[array.length] = allChildren[i]
      array.length += 1
    }
  }
  return array
}
Node.prototype.addClass = function (classes) {
  classes.forEach( (value) => this.classList.add(value) )
}

item3.getSiblings()
// item3.getSiblings.call(item3)
item3.addClass(['a','b','c'])
// item3.addClass.call(item3, [abc])
  1. Node2无侵入
window.jQuery = ???
window.$ = jQuery

var $div = $('div')
$div.addClass('red') // 可将所有 div 的 class 添加一个 red
$div.setText('hi') // 可将所有 div 的 textContent 变为 hi

实现代码如下

window.jQuery = function(nodeOrSelector) {
let nodes = {}
if( typeof nodeOrSelector === 'string' ){
let temp = document.querySelectorAll (nodeOrSelector) //伪数组
for(let i=0 ; i<temp.length ; i++ ) {
nodes[i] = temp[i]
}
nodes.length = temp.length
}else if (nodeOrSelector instanceof Node){
nodes = {
0:nodeOrSelector ,
length:1
}
}

nodes.addClass = function ( classes ) {
classes.forEach( (value) => {
for( let i=0 ; i< nodes.length ; i++ ){
nodes[i].classList.add(value)
}
})
}
nodes.getText = function(){
  var texts = []
  for(let i = 0;i< nodes.length;i++){
    texts.push(node[i].textContent)
  }
  return texts
}
nodes.setText = function(text){
  for(let i = 0; i<nodes.length;i++){
    nodes[i].textContent = text
  }
}
return nodes

}

window.$ = jQuery
var $div = jQuery('div')
$div.addClass(['red'])
$div.setText('hi')



首先接受一个node或者选择器
把它封装成伪数组
为数组加上几个API然后返回nodes
声明一个node2=jQuery(‘选择器’),本质上是哈希
声明一个 $div=jQuery(‘选择器’),本质上是哈希

相关文章

网友评论

      本文标题:2019-03-24 jQuery

      本文链接:https://www.haomeiwen.com/subject/zzrpvqtx.html