javascript 实现一种类似于jQuery的delegate,on ,live的事件绑定机制
jQuery虽然好用但是,对于一些页面来说其实是没有并要加载这么大一个文件的,为了应对这个情况 ,对于jQuery的中各种方法我们就要能够自己去实现
下面是用js实现jQuery中的delegate
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
function Is(dom, selector) { if (!selector) { return false; } if (~selector.indexOf('#')) {//ID选择器 if ('#'+dom.id == selector ) { return true; } return false; } if (~selector.indexOf('.')) {//样式选择器 if (dom.classList && dom.classList.contains && dom.classList.contains(selector.substring(1,selector.length-1))) { return true; } if ('.'+dom.className == selector) { return true; } return false; } //只有三种选择器,id class tagName if (dom.tagName == selector ) { return true; } return false; } Element.prototype.On = function (selector, event, data, func) { if (data instanceof Function) { func = data; data = null; } this.addEventListener(event, function (e) { e = e || event; var currentElement = e.srcElement; if (Is(currentElement,selector)) { func.call(currentElement, data); } }); }; var ns = document.getElementsByTagName('body'); for (var i in ns) { ns[i].On('.questionText', 'click', function () { alert("Success"); }); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <script type="text/javascript"> //Survey("123"); </script> <script id="form" type="text/javascript"> function Is(dom, selector) { if (!selector) { return false; } if (~selector.indexOf('#')) {//ID选择器 if ('#'+dom.id == selector ) { return true; } return false; } if (~selector.indexOf('.')) {//样式选择器 if (dom.classList && dom.classList.contains && dom.classList.contains(selector.substring(1,selector.length-1))) { return true; } if ('.'+dom.className == selector) { return true; } return false; } //只有三种选择器,id class tagName if (dom.tagName == selector ) { return true; } return false; } Element.prototype.On = function (selector, event, data, func) { if (data instanceof Function) { func = data; data = null; } this.addEventListener(event, function (e) { e = e || event; var currentElement = e.srcElement; if (Is(currentElement,selector)) { func.call(currentElement, data); } }); }; var ns = document.getElementsByTagName('body'); for (var i in ns) { ns[i].On('.questionText', 'click', function () { alert("Success"); }); } </script> <div> <textarea class="questionText" style="width:90%;height:auto; resize:none;"></textarea> </div> <div style="border:1px solid red;height:300px;"> werw </div> </body> </html>