标签:attr function 部分 down win ice target return rip
// 实现一个简单的Query function $(selector) { var firstChar = selector.charAt(0); if (firstChar == "#") { var len = selector.split(" "); if (len.length == 1) { return document.getElementById(selector.slice(1,selector.length)); } else { var resu = []; var getId = document.getElementById(len[0].slice(1,len[0].length)); for (var i = 0; i < getId.children.length; i++) { if(getId.children[i].className == len[1].slice(1,len[1].length)) { resu.push(getId.children[i]); }; } return resu[0]; } } else if (firstChar == ".") { return document.getElementsByClassName(selector.slice(1,selector.length))[0]; } else if (firstChar == "[") { if (selector.match(/=/)) { var index = selector.indexOf("="); var cao1 = selector.slice(1,index); var cao2 = selector.slice(index+1,selector.length-1); var all = document.getElementsByTagName(‘*‘); var res1 = []; for (var i = 0; i < all.length; i++) { if(all[i].getAttribute(cao1)&&all[i].getAttribute(cao1) == cao2) { res1.push(all[i]); } } return res1[0]; } else { var cao = selector.slice(1,selector.length-1); var all = document.getElementsByTagName(‘*‘); var res = []; for (var i = 0; i < all.length; i++) { if(all[i].getAttribute(cao)) { res.push(all[i]); } } return res[0]; } } else { return document.getElementsByTagName(selector)[0]; } } // 给一个element绑定一个针对event事件的响应,响应函数为listener function addEvent(element, event, listener) { // your implement element.addEventListener(event,listener,false); } // 移除element对象对于event事件发生时执行listener的响应 function removeEvent(element, event, listener) { // your implement element.removeEventListener(event,listener,false); } // 实现对click事件的绑定 function addClickEvent(element, listener) { // your implement addEvent(element,"click",listener); } // 实现对于按Enter键时的事件绑定 function addEnterEvent(element, listener) { // your implement element.onkeyDown = function(event) { var e = event || window.event; if (e&&e.keyCode == 13) { listener(); } } } function delegateEvent(element, tag, eventName, listener) { $.on(element,eventName,function(){ var e = event ||window.event; var target = e.target ||e.srcElement; if (target.tagName == tag) { listener(); } }) }
$.on = addEvent;
$.un = removeEvent;
$.click = addClickEvent;
$.enter = addEnterEvent;
$.delegate = delegateEvent;
百度前端技术学院2015JavaScript基础部分实现自己的小型jQuery
标签:attr function 部分 down win ice target return rip
原文地址:http://www.cnblogs.com/zhixuanziben/p/6106982.html