模仿jQuery封装一个函数

目的:模仿jQuery的使用模式封装一个函数,并增加一个新方法
基本思路:声明一个函数,该函数接受一个参数并返回一个新对象,该对象有一个属性的值为函数。

function jDom(selector){
  let currentNode = document.querySelector(selector)
  let jObj = {0:curentNode,length:1}
  jObj.getSiblings = function(){}
  return jObj
}

P

新增方法为获取一个元素的所有兄弟元素,使用DOM的API来实现。

var getSiblings = function(currentNode){
  let allChild = currentNode.parentNode.children
  let siblings = {length:0}
  for(let i = 0;i

把这个函数作为匿名函数赋值给jObj的getsiblings属性

window.$ = jDom

最后可以像jQuery那样操作,获得id为hero的标签的所有兄弟元素。

$('#hero').getSiblings.call()

你可能感兴趣的:(模仿jQuery封装一个函数)