手写简易 jQuery 考虑插件和扩展性
首先准备一个基本的 dom
js
<p>文字1</p>
<p>文字2</p>
<p>文字3</p>
大神手写简易 jQuery
js
//基本的操作
class jQuery {
constructor(selector) {
const result = document.querySelectorAll(selector);
const length = result.length;
for (let i = 0; i < length; i++) {
this[i] = result[i];
}
this.length = length;
}
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);
});
}
}
可以这样来运行
js
const $p = new jQuery('p');
console.log($p.get(1)); //<p>文字2</p>
$p.on('click', () => alert('clicked')); // clicked
下面来考虑下插件和扩展性,那就可以这样写完事
js
//插件
jQuery.prototype.dialog = function (info) {
alert(info);
};
$p.dialog('info'); // info
//扩展‘造轮子’
class myJQuery extends jQuery {
constructor(selector) {
super(selector);
}
//扩展自己方法
addClass(className) {}
style(data) {}
}