实现一个 jQuery 的 API
<!--html代码-->
<body>
<h1>text</h1>
<ul>
<li id="item1">选项1</li>
<li id="item2">选项2</li>
<li id="item3">选项3</li>
</ul>
</body>
封装函数
- 获取目标元素的所有兄弟元素
//javaScript代码
function getSiblings(node) {
var allChlidren = node.parentNode.chlidren
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
}
//调用方法
getSiblings(item3)
- 给目标元素添加class
//javaScript代码
function addClass(node,classes){
for (let key in classes){
var value = classes[key]
var methodName = value? ' add ' : ' remove '
node.classList[methodName](key)
}
}
// 调用addClass()
addClass ( node,{a:true , b:false,c:true } )
命名空间
//javaScrip代码
var dom={}
dom.getSiblings=function (node) {
var allChlidren = node.parentNode.chlidren
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
}
dom.addClass = function (node,classes){
for (let key in classes){
var value = classes[key]
var methodName = value? ' add ' : ' remove '
node.classList[methodName](key)
}
}
//调用方法
dom.getSiblings( node )
dom.addClass ( node,{a:true , b:false,c:true } )
扩展 Node 接口
- 直接在 Node.prototype 上加函数
Node.prototype.getSiblings =function () {
var allChlidren = this.parentNode.chlidren
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){
for (let key in classes){
var value = classes[key]
var methodName = value? ' add ' : ' remove '
this.classList[methodName](key)
}
}
- 无侵入,新的接口
window.Node2 = 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]
}
node.length = i
}else if (nodeOrSelector instanceof Node){
nodes = {
0:nodeSelector ,
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(nodes[i].textContent)
}
nodes.setText = function (text){
for ( let i=0 ; i<nodes.length ; i++ ){
nodes[ i ] .textContext = text
}
}
return nodes
}
- 改个名字
Node2改成jQuery
- 给个缩写
window.$ = jQuery
至此,实现了一个 jQuery 的 API