1凝化、封裝
獲取當(dāng)前元素的兄弟元素
/*1. 獲取當(dāng)前元素的所有兄弟元素 */
window.customDom = {}
customDOM.getAllSiblings = function (node) {
let allChildren = node.parentNode.children
let array = {length: 0}
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== node) {
array[array.length] = allChildren[i]
array.length++
}
}
return array
}
/*2. 一次性添加多個(gè)class*/
/*通過(guò)遍歷數(shù)組來(lái)添加多個(gè)class*/
customDOM.addClass = function (node, class) {
for (let key in class) {
let value = class[key]
let method = value ? 'add' : 'remove'
node.classList[method](key)
}
}
/*增加命名空間*/
window.customDOM = {}
customDOM.getAllSiblings = getAllSiblings()
customDOM.addClass = addClass()
上面代碼我們根據(jù)提供的node節(jié)點(diǎn)獲取父節(jié)點(diǎn)的所有子節(jié)點(diǎn),然后遍歷這個(gè)子節(jié)點(diǎn)形成一個(gè)新的偽數(shù)組酬荞,就可以獲得操作節(jié)點(diǎn)的所有兄弟元素搓劫。然后操作獲取的偽數(shù)組來(lái)進(jìn)行批量添加class,經(jīng)過(guò)封裝后我們可以通過(guò)調(diào)用函數(shù)的方式實(shí)現(xiàn)這個(gè)功能混巧,調(diào)用方法如下:
customDom.getAllSiblings(item3)
但對(duì)于我們來(lái)說(shuō)經(jīng)常使用的調(diào)用方法是下面這種:
item3.getAllSiblings(item3)
若要實(shí)現(xiàn)下面這種更為合理的調(diào)用方式我們可以將該功能直接寫(xiě)入Node的共用屬性里:
/*1. 獲取當(dāng)前元素的所有兄弟元素 */
Node.prototype.getAllSiblings = function () {
let allChildren = this.parentNode.children
let array = {length: 0}
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== this) {
array[array.length] = allChildren[i]
array.length++
}
}
return array
}
/*2. 一次性添加多個(gè)class*/
/*通過(guò)遍歷數(shù)組來(lái)添加多個(gè)class*/
Node.prototype.addClass = function (class) {
for (let key in class) {
let value = class[key]
let method = value ? 'add' : 'remove'
this.classList[method](key)
}
}
item3.addClass({a: true, b: false, c:true)
//item3.addClass.call(item3, {a: true, b: false, c:true})
這里的this就是方法被調(diào)用時(shí)前面的對(duì)象枪向。
通過(guò)上面代碼將函數(shù)功能寫(xiě)入共用屬性我們就可以直接通過(guò)API的形式直接調(diào)用。
但是咧党,我們直接更改共用屬性的函數(shù)可能會(huì)被別人更改或者覆蓋掉秘蛔,我們可以這樣做:
window.Node2 = function (node) {
return {
/*1. 獲取當(dāng)前元素的所有兄弟元素 */
getAllSiblings: function () {
let allChildren = node.parentNode.children
let array = {length: 0}
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== node) {
array[array.length] = allChildren[i]
array.length++
}
}
return array
},
/*2. 一次性添加多個(gè)class*/
addClass: function (class){
for (let key in class) {
let value = class[key]
let method = value ? 'add' : 'remove'
node.classList[method](key)
}
}
}
}
let node2 = Node2(item3)
node2.getAllSiblings()
node2.addClass({a: true, b: false, c: true})
這里Node2是一個(gè)函數(shù),我們想獲得方法就變成了Node2函數(shù)的返回值,調(diào)用時(shí)的參數(shù)item3在Node2中已經(jīng)傳了深员。這種調(diào)用方法更簡(jiǎn)潔负蠕。如果我們把Node2的名字改為:jquery。由此我們可以看出:jQuery()實(shí)際上是一個(gè)構(gòu)造函數(shù)倦畅,它接收一個(gè)參數(shù)遮糖,這個(gè)參數(shù)可以是一個(gè)節(jié)點(diǎn)或選擇器(用來(lái)選擇某個(gè)元素或節(jié)點(diǎn)),然后返回一個(gè)方法對(duì)象去操作節(jié)點(diǎn)滔迈。(對(duì)其進(jìn)行某種操作)止吁。