手写一个简易的jquery
Jquery虽然作为一个JS库因为MVVM结构出现,目前使用不多 ,但是对于JS的提升还是又很大的帮助的,接下来我门手写一个简易jquery
//创建Jqery类 拿到所有符合类
class jquery{
constructor(seletor){
const result= document.querySelectorAll(seletor)
for(let i=0 ;i<result.length;i++){
this[i]=result[i]
}
this.length=result.length
this.seletor=seletor
}
//获取该数组下某一DOM结构方法
get(index){
return this[index]
}
//选取所有元素
each(fn){
for(let i=0; i<this.length;i++ ){
let elem=this[i]
console.log(elem)
fn(elem)
}
}
// 为元素添加 事件
on(type,fn){
return this.each((elem=>{
elem.addEventListener(type,fn,false)
}))
}
}
const $p=new jquery('p')
console.log($p)
console.log($p.each)
$p.each((elem)=>{
console.log(elem.innerHTML)
})
$p.on('click' ,(e)=>{
console.log(e.target.innerHTML)
})
// $是通过封装一个函数
var $=function(seletor){
return new jquery(seletor)
}
目前简易类 未考虑插件的使用
如有错误大家多多指教