手写简易jQuery,考虑插件和扩展性

html

<body>
	<p>这是一段文字1</p>
    <p>这是一段文字2</p>
    <p>这是一段文字3</p>
    <p>这是一段文字4</p>
</body>

js

<script>
	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;
		    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);
		    })
		}
		
		// 扩展更多DOM API
		}
		
		const $p = new jQuery('p');
		$p.get(0);
		$p.each((elem) => console.log(elem.nodeName))
		$p.on('click', () => {
		alert('点击');
		})
		
		// 插件
		jQuery.prototype.dialog = function(info){
		alert(info);
		}
		
		// 造轮子
		class myJQuery extends jQuery{
		constructor(selector){
		    super(selector);
		}
		//扩展自己的方法
		addClass(className){
		
		}
	}
</script>
发布了23 篇原创文章 · 获赞 0 · 访问量 521

猜你喜欢

转载自blog.csdn.net/qq_33084055/article/details/103825099