/*修改Node的原型链*/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<ul>
<li id="item1">选项1</li>
<li id="item2">选项2</li>
<li id="item3">选项3</li>
<li id="item4">选项4</li>
<li id="item5">选项5</li>
</ul>
</body>
</html>
------------------------------------------------------------
/*修改Node的原型链*/
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){
for(let key in classes){
var value = classes[key]
var methodName = value ? 'add' : 'remove'
this.classList[methodName](key)
}
}
console.dir(item3)
console.log(item3)
console.log(item3.getSiblings())
console.log(item3.addClass({'a':true,'b':true,'c':true}))
console.log(item3.getSiblings.call(item3))
console.log(item3.addClass.call(item3,{'a':true,'b':true,'c':true}))
------------------------------------------------------------------------------
-----------------------Node2[无侵入]---------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<ul>
<li id="item1">选项1</li>
<li id="item2">选项2</li>
<li id="item3">选项3</li>
<li id="item4">选项4</li>
<li id="item5">选项5</li>
</ul>
</body>
</html>
----------------------------------------------------------------------------
window.Node2 = function(node){
return{
getSiblings:function(){
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
},
addClass:function(classes){
for(let key in classes){
var value = classes[key]
var methodName = value ? 'add' : 'remove'
node.classList[methodName](key)
}
}
}
}
var node2 = Node2(item3)
console.log(Node2)
console.log(node2)
console.log(node2.getSiblings())
node2.addClass({'a':true,'b':true,'c':true})
console.log(item3)
网友评论