链式调用就是在每个方法执行完成之后都将当前this放回,这样接下来的方法便都可以拿到这个对象并接着调用,所以我们可以先拓展几个常用的jquery的方法
on方法的实现,由于各浏览器的兼容性问题,所以我们对事件绑定方式on进行一个简单的实现,还是要用到我们的extend方法,因为选择器返回的对象都可以调用这个方法,所以我们将其拓展到A.fn对象上面
A.fn.extend({ // 立即执行函数获取各浏览器下的绑定方式并绑定到on方法上,避免每次调用都要判断浏览器环境 on: (function(){ if(document.addEventListener) { return function(type, fn){ for(let i = 0; i < this.length; i++) { this[i].addEventListener(type, fn, false) } } } else if(document.addEvent) { return function(type, fn){ for(let i = 0; i < this.length; i++) { this[i].addEvent('on'+type, fn) } } } else { return function(type, fn){ for(let i = 0; i < this.length; i++) { this[i]['on' + type] = fn } } } })() }) a.on('click', function(){ console.log(this.innerHTML) // 1 }) 上面我们对A.fn进行了拓展,使所有选择器返回的对象都可以进行数据绑定,并且可以成功打印1接下来我们依次对其进行attr,css,html方法的拓展,在对css方法进行拓展的时候我们先对A进行了拓展,使其拥有可以将-连接的css属性转为驼峰命名的css属性,从而实现我们的赋值 A.extend({ // 常用css转驼峰 cameName: function(str){ return str.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase() }) } }) A.fn.extend({ attr: function(...args){ if(args.length < 1) { return } if(args.length === 1) { if(typeof args[0] === 'string') { return this[0].getAttribute(args[0]) } else { for(let i = 0; i < this.length; i++) { for(let key in args[0]) { this[i].setAttribute(key, args[0][key]) } } } } else { for(let i = 0; i < this.length; i++) { this[i].setAttribute(args[0], args[1]) } } return this }, html: function(...args){ console.log(args) if(args.length) { for(let i = 0; i < this.length; i++) { this[i].innerHTML = args[0] } return this } else { return this[0].innerHTML } }, css: function(...args){ if(args.length < 1) { return } if(args.length === 1) { const name = args[0] if(typeof args[0] === 'string') { if(this[0].currentStyle){ return this[0].currentStyle[name] } else { return getComputedStyle(this[0], false)[name] } }else if(typeof args[0] === 'object') { for(let i = 0; i < this.length; i++) { for(let key in args[0]) { this[i].style[A.cameName(key)] = args[0][key] } } } } else { const name = args[0] for(let i = 0; i < this.length; i++) { this[i].style[A.cameName(name)] = args[1] } } return this } }) 上面我们就实现了jquery常用的几个方法与链式调用,下面我们就可以使用上面的方法进行调用 a.css('background-color', '#0f0').html('我是链式调用').attr('data-tag', 'div').on('click', function(){ alert(this.innerHTML) })