看了网上的一些资料,发现有一下几种比较牛的:
john resig的 <!---->Flexible Javascript Events(The code, itself, is very short and simple - only 15 lines long:
)
function addEvent( obj, type, fn ) { if ( obj.attachEvent ) { obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn]( window.event );} obj.attachEvent( 'on'+type, obj[type+fn] ); } else obj.addEventListener( type, fn, false ); } function removeEvent( obj, type, fn ) { if ( obj.detachEvent ) { obj.detachEvent( 'on'+type, obj[type+fn] ); obj[type+fn] = null; } else obj.removeEventListener( type, fn, false ); }
dean.edwards 发表了自己的意见:
<!---->My solution is very different.
- it performs no object detection
- it does not use the addeventListener/attachEvent methods
- it keeps the correct scope (the this keyword)
- it passes the event object correctly
- it is entirely cross-browser (it will probably work on IE4 and NS4)
- and from what I can tell it does not leak memory
// written by Dean Edwards, 2005 // with input from Tino Zijdel, Matthias Miller, Diego Perini // http://dean.edwards.name/weblog/2005/10/add-event/ function addEvent(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else { // assign each event handler a unique ID if (!handler.$$guid) handler.$$guid = addEvent.guid++; // create a hash table of event types for the element if (!element.events) element.events = {}; // create a hash table of event handlers for each element/event pair var handlers = element.events[type]; if (!handlers) { handlers = element.events[type] = {}; // store the existing event handler (if there is one) if (element["on" + type]) { handlers[0] = element["on" + type]; } } // store the event handler in the hash table handlers[handler.$$guid] = handler; // assign a global event handler to do all the work element["on" + type] = handleEvent; } }; // a counter used to create unique IDs addEvent.guid = 1; function removeEvent(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else { // delete the event handler from the hash table if (element.events && element.events[type]) { delete element.events[type][handler.$$guid]; } } }; function handleEvent(event) { var returnValue = true; // grab the event object (IE uses a global event object) event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event); // get a reference to the hash table of event handlers var handlers = this.events[event.type]; // execute each event handler for (var i in handlers) { this.$$handleEvent = handlers[i]; if (this.$$handleEvent(event) === false) { returnValue = false; } } return returnValue; }; function fixEvent(event) { // add W3C standard event methods event.preventDefault = fixEvent.preventDefault; event.stopPropagation = fixEvent.stopPropagation; return event; }; fixEvent.preventDefault = function() { this.returnValue = false; }; fixEvent.stopPropagation = function() { this.cancelBubble = true; };
最后 dean.edwards 推荐了一种:
/** * Crossbrowser event handling functions. * * A set of functions to easily attach and detach event handlers to HTML elements. * These functions work around the shortcomings of the traditional method ( element.onevent = function; ) * where only 1 handler could be attached for a certain event on the object, and mimic the DOM level 2 * event methods addEventListener and removeEventListener for browsers that do not support these * methods (e.g. Internet Explorer) without resorting to propriety methods such as attachEvent and detachEvent * that have a whole set of their own shortcomings. * Created as an entry for the 'contest' at quirksmode.org: http://www.quirksmode.org/blog/archives/2005/09/addevent_recodi.html * * @author Tino Zijdel ( crisp@xs4all.nl ) * @version 1.2 * @date 2005-10-21 */ /** * addEvent * * Generic function to attach event listeners to HTML elements. * This function does NOT use attachEvent but creates an own stack of function references * in the DOM space of the element. This prevents closures and therefor possible memory leaks. * Also because of the way the function references are stored they will get executed in the * same order as they where attached - matching the behavior of addEventListener. * * @param obj The object to which the event should be attached. * @param evType The eventtype, eg. 'click', 'mousemove' etcetera. * @param fn The function to be executed when the event fires. * @param useCapture (optional) Whether to use event capturing, or event bubbling (default). */ function addEvent(obj, evType, fn, useCapture) { //-- Default to event bubbling if (!useCapture) useCapture = false; //-- DOM level 2 method if (obj.addEventListener) { obj.addEventListener(evType, fn, useCapture); } else { //-- event capturing not supported if (useCapture) { alert('This browser does not support event capturing!'); } else { var evTypeRef = '__' + evType; //-- create function stack in the DOM space of the element; seperate stacks for each event type if (obj[evTypeRef]) { //-- check if handler is not already attached, don't attach the same function twice to match behavior of addEventListener if (array_search(fn, obj[evTypeRef]) > -1) return; } else { //-- create the stack if it doesn't exist yet obj[evTypeRef] = []; //-- if there is an inline event defined store it in the stack if (obj['on'+evType]) obj[evTypeRef][0] = obj['on'+evType]; //-- attach helper function using the DOM level 0 method obj['on'+evType] = IEEventHandler; } //-- add reference to the function to the stack obj[evTypeRef][obj[evTypeRef].length] = fn; } } } /** * removeEvent * * Generic function to remove previously attached event listeners. * * @param obj The object to which the event listener was attached. * @param evType The eventtype, eg. 'click', 'mousemove' etcetera. * @param fn The listener function. * @param useCapture (optional) Whether event capturing, or event bubbling (default) was used. */ function removeEvent(obj, evType, fn, useCapture) { //-- Default to event bubbling if (!useCapture) useCapture = false; //-- DOM level 2 method if (obj.removeEventListener) { obj.removeEventListener(evType, fn, useCapture); } else { var evTypeRef = '__' + evType; //-- Check if there is a stack of function references for this event type on the object if (obj[evTypeRef]) { //-- check if function is present in the stack var i = array_search(fn, obj[evTypeRef]); if (i > -1) { try { delete obj[evTypeRef][i]; } catch(e) { obj[evTypeRef][i] = null; } } } } } /** * IEEventHandler * * IE helper function to execute the attached handlers for events. * Because of the way this helperfunction is attached to the object (using the DOM level 0 method) * the 'this' keyword will correctely point to the element that the handler was defined on. * * @param e (optional) Event object, defaults to window.event object when not passed as argument (IE). */ function IEEventHandler(e) { e = e || window.event; var evTypeRef = '__' + e.type, retValue = true; //-- iterate through the stack and execute each function in the scope of the object by using function.call for (var i = 0, j = this[evTypeRef].length; i < j; i++) { if (this[evTypeRef][i]) { if (Function.call) { retValue = this[evTypeRef][i].call(this, e) && retValue; } else { //-- IE 5.0 doesn't support call or apply, so use this this.__fn = this[evTypeRef][i]; retValue = this.__fn(e) && retValue; } } } if (this.__fn) try { delete this.__fn; } catch(e) { this.__fn = null; } return retValue; } /** * array_search * * Searches the array for a given value and returns the (highest) corresponding key if successful, -1 if not found. * * @param val The value to search for. * @param arr The array to search in. */ function array_search(val, arr) { var i = arr.length; while (i--) if (arr[i] && arr[i] === val) break; return i; }
短的版本:
/** * Generic add/removeEvent functionality * * @author Tino Zijdel ( crisp@xs4all.nl ) * @version 1.2 (short version) * @date 2005-10-21 */ function addEvent(obj, evType, fn) { var evTypeRef = '__' + evType; if (obj[evTypeRef]) { if (array_search(fn, obj[evTypeRef]) > -1) return; } else { obj[evTypeRef] = []; if (obj['on'+evType]) obj[evTypeRef][0] = obj['on'+evType]; obj['on'+evType] = handleEvent; } obj[evTypeRef][obj[evTypeRef].length] = fn; } function removeEvent(obj, evType, fn) { var evTypeRef = '__' + evType; if (obj[evTypeRef]) { var i = array_search(fn, obj[evTypeRef]); if (i > -1) delete obj[evTypeRef][i]; } } function handleEvent(e) { e = e || window.event; var evTypeRef = '__' + e.type, retValue = true; for (var i = 0, j = this[evTypeRef].length; i < j; i++) { if (this[evTypeRef][i]) { this.__fn = this[evTypeRef][i]; retValue = this.__fn(e) && retValue; } } if (this.__fn) try { delete this.__fn; } catch(e) { this.__fn = null; } return retValue; } function array_search(val, arr) { var i = arr.length; while (i--) if (arr[i] && arr[i] === val) break; return i; }
不过我还是用了john resig 的。。。
相关推荐
- 事件处理:JavaScript可以监听和响应用户交互,通过addEventListener和removeEventListener来绑定和解绑事件。 - DOM操作:通过DOM API可以查找、添加、删除和修改HTML元素,实现页面动态更新。 6. **异步编程*...
初学者可以通过查阅这个CHM文件了解如何选择DOM元素、执行DOM操作、绑定事件、创建动画,以及使用Ajax进行异步通信。jQuery的核心功能包括选择器(用于快速定位DOM元素)、链式操作(让代码更简洁)、插件机制(扩展...
事件处理器可以绑定在元素上,通过addEventListener和removeEventListener来添加和移除。 五、AJAX与Fetch 异步JavaScript和XML(AJAX)允许我们在不刷新页面的情况下与服务器交换数据并更新部分网页内容。现代...
这篇读书笔记主要探讨了在组件特殊场景下如何手动绑定事件,特别是处理React未提供的一些事件,以及解决在使用`e.stopPropagation()`和`e.preventDefault()`时遇到的问题。同时,笔记也涉及了如何在React组件中与...
Vue.js学习笔记 Vue.js是一个轻量级的前端JavaScript框架,它以其易用性、灵活性和高效性而受到开发者的青睐。Vue的核心功能是能够将页面上的功能模块化开发,即通过组件化的方式构建前端界面,从而提高开发效率...
以上是JavaScript学习笔记中提到的一些核心知识点,通过对这些知识点的理解和熟练应用,可以为进一步学习和掌握JavaScript打下坚实的基础。在实际开发过程中,结合具体的项目需求,这些知识会得到更深入的拓展和应用...
- **事件绑定**:可以通过不同的方式为HTML元素绑定事件处理器。 - 对于Internet Explorer浏览器,使用`attachEvent`方法。 ```javascript function add() { alert("hello event!"); } var div = document....
在韩顺平的JavaScript笔记中,他深入讲解了JS面向对象编程的各个方面,包括变量的作用域、对象引用、this关键字的使用以及对象的方法。 首先,变量的作用域在JavaScript中是一个关键概念。带var和不带var声明的变量...
- Vue.js:轻量级且易于上手的前端框架,提供声明式渲染和响应式数据绑定。 - jQuery:简化DOM操作、事件处理和Ajax请求的流行库。 9. **实战案例** - 表单验证:利用JavaScript进行客户端验证,提高用户体验。 ...
JavaScript 高级笔记 - 函数的定义和调用、this 指向和改变、严格模式 JavaScript 中的函数定义和调用是编程语言的基础。函数可以定义多种方式,包括函数声明、函数表达式和 new Function()。函数的调用方式也多种...
5. **事件处理**:jQuery的`.on()`方法可以绑定多种类型的事件,如点击、改变等,并提供了简化的事件处理函数语法。 6. **Ajax请求**:jQuery的`.ajax()`和衍生方法如`.get()`, `.post()`,简化了异步数据请求,...
本文档为本人学习js时候做的笔记,只需要仅仅两个币就可以了,其中内容包括简单的数据类型,创建对象,数组,包装类BOM和DOM,其中重点的DOM包括基本的事件对象操作,轮盘绑定定时器,还有附加的一点点js高级部分...
Vue.js的动态数据绑定是其核心特性之一,它使得数据模型与视图之间的交互变得简单。在Vue中,数据绑定是双向的,意味着视图的变化会反映到数据模型上,反之亦然。以下是对这一机制的详细解释: 首先,我们要理解四...
- **响应式数据绑定**:Vue.js的`data`属性采用双向数据绑定,当数据发生变化时,视图会自动更新。 2. **Vuex状态管理** - 在大型应用中,为了协调组件间的共享状态,Vue项目通常使用Vuex进行集中式的状态管理。...
数据绑定是AngularJS的核心特性之一,它允许开发者通过声明式的方式将模型(model)和视图(view)关联起来。AngularJS提供了一种机制,可以实现模型和视图之间的同步更新,也就是说,当模型的数据发生变化时,视图也会...
JS 逻辑交互可以使用 JavaScript 语言,实现了小程序的交互功能。 六、宿主环境简介 宿主环境是小程序的运行环境,提供了小程序的运行基础设施。宿主环境包括了小程序的运行机制、通信模型和组件分类等。 七、...
此外,JavaScript还提供了DOM操作、事件处理、AJAX(异步JavaScript和XML)以及WebSocket等与浏览器交互的能力。 在学习Vue、CSS和JavaScript时,理解它们如何协同工作至关重要。Vue中的组件可以通过CSS作用域隔离...
Vue.js是目前前端开发领域非常流行的JavaScript框架,它以其易学易用、高效灵活的特点深受开发者喜爱。Vue.js的设计理念是让开发更加简洁,通过声明式的数据绑定和组件化开发,使得构建用户界面的工作变得更加简单。...