代码
class jQuery {
constructor(selector) {
const result = document.querySelectorAll(selector) // DOM查询
const length = result.length
for (let i = 0; i < length; i++) {
this[i] = result[i]
}
this.length = length
this.selector = selector
}
get (index) {
return this[index]
}
each (fn) {
for (let i = 0; i < this.length; i++) {
const elem = this[i]
fn(elem)
}
}
on (type, fn) {
return this.each(elem => {
elem.addEventListener(type, fn, false)
})
}
// 还可以拓展很多API
}
//插件
jQuery.prototype.dialog=function(info) {
alert(info)
}
//基于 jQuery "造轮子"
class myjQuery extends jQuery {
constructor(selector) {
super(selector)
}
// 扩展自己的方法
addClass () {
}
}
// 测试
const $p = new jQuery('p')
$p
// jQuery {0: p, 1: p, 2: p, length: 3, selector: "p"}
$p.get(1)
{/* <p>文字2</p> */ }
$p.each((elem) => console.log(elem.nodeName))
// ppp
$p.on('click', () => alert('clicked!'))
$p.dialog('abc')
// abc