原文地址:Bougie的博客
jQuery作為曾經(jīng)Web前端的必備利器粟瞬,隨著MVVM框架的興起寝优,如今已稍顯沒(méi)落且轨。但它操作DOM的便利性無(wú)出其右。我用ES6寫了一個(gè)基于class簡(jiǎn)化版的jQuery礁叔,包含基礎(chǔ)DOM操作,支持鏈?zhǔn)讲僮髌。瑑H供日常使用琅关。當(dāng)然,它不支持IE讥蔽。
構(gòu)造器(constructor)
構(gòu)造一個(gè)tinyJquery對(duì)象涣易。功能:基于基本選擇器構(gòu)造,包括id勤篮、class都毒、tagName;基于原生DOM構(gòu)造碰缔,將原生DOM對(duì)象轉(zhuǎn)化為tinyJquery對(duì)象账劲。為支持批量操作,tinyJquery構(gòu)造器應(yīng)包含復(fù)數(shù)的DOM金抡。
class tinyJquery {
constructor(name) {
if (typeof name == 'string') {
this.dom = document.querySelectorAll(name)
} else if (name.constructor.name == 'NodeList' || Array.isArray(name)){
this.dom = name
} else {
this.dom = [name]
}
}
}
使用$函數(shù)構(gòu)建tinyJquery對(duì)象
function $(name) {
return new tinyJquery(name)
}
方法(后續(xù)會(huì)漸漸完善)
event操作
// addEventListener
on(eventName, fn, bubble = false) {
this.dom.forEach(i => {
i.addEventListener(eventName, fn, !bubble)
})
return $(this.dom)
}
// removeEventListener
un(eventName, fn, bubble = false) {
this.dom.forEach(i => {
i.removeEventListener(eventName, fn, !bubble)
})
return $(this.dom)
}
class操作
// addClass
ac(className) {
this.dom.forEach(i => {
i.classList.add(className)
})
return $(this.dom)
}
// removeClass
rc(className) {
this.dom.forEach(i => {
i.classList.remove(className)
})
return $(this.dom)
}
// toggleClass
tc(className) {
this.dom.forEach(i => {
i.classList.toggle(className)
})
return $(this.dom)
}
// containClass
cc(className) {
let flag = false
this.dom.forEach(i => {
if(i.classList.contains(className)) flag = true
})
return flag
}
屬性操作
// set inline style
css(obj) {
this.dom.forEach(v => {
Object.keys(obj).forEach(i => {
v.style[i] = obj[i]
})
})
return $(this.dom)
}
// get or set input value
val(val) {
if(val) {
this.dom[0].value = val
return $(this.dom)
} else {
return this.dom[0].value
}
}
內(nèi)容操作
// get or set dom innerHtml
html(val) {
if(val) {
this.dom.forEach(i => {
i.innerHTML = val
})
return $(this.dom)
} else {
return this.dom[0].innerHTML
}
}
// get or set attribute
attr(key, val) {
if(key && !val) {
return this.dom[0].getAttribute(key)
} else {
this.dom.forEach(i => {
i.setAttribute(key, val)
})
return $(this.dom)
}
}
表單操作
// get JSONData
serializeObject() {
let dom = this.dom[0], obj = {}
dom.querySelectorAll('input, textarea').forEach(i => {
obj[i.getAttribute('name')] = i.value
})
return obj
}
// get FormData
serializeForm() {
let dom = this.dom[0], form = new FormData()
dom.querySelectorAll('input, textarea').forEach(i => {
form.append(i.getAttribute('name'), i.value)
})
return form
}
2018-04-16更新
Dom獲取
// parent
parent() {
return $(this.dom[0].parentNode)
}
// siblings
siblings() {
let dom = this.dom[0]
var a = [];
var p = dom.parentNode.children;
for (var i = 0, pl = p.length; i < pl; i++) {
if (p[i] !== dom) a.push(p[i]);
}
// console.log(Array.isArray(a))
return $(a)
}
遍歷
// each
each(callback) {
// this.dom.forEach(i => {
// // callback.bind(i)()
// callback.call(i, null)
// })
this.dom.forEach(i => {
callback($(i))
})
}