Home > Web Front-end > JS Tutorial > JavaScript implements cross-browser adding and deleting event binding function examples_javascript skills

JavaScript implements cross-browser adding and deleting event binding function examples_javascript skills

WBOY
Release: 2016-05-16 15:47:14
Original
1086 people have browsed it

The example in this article describes the JavaScript implementation of cross-browser adding and deleting event binding functions. Share it with everyone for your reference. The details are as follows:

The event binding function of IE is attachEvent; while Firefox and Safari are addEventListener; Opera supports both. Using jQuery, you can use simple bind(), or functions such as $().click() to solve the problem. If you are not using a JavaScript framework, you can use the following encapsulated bind() function.

Add event binding bind()

/************************************
* 添加事件绑定
* @param obj  : 要绑定事件的元素
* @param type : 事件名称。不加 "on". 如 : "click" 而不是 "onclick".
* @param fn  : 事件处理函数
************************************/
function bind( 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);
}

Copy after login

For example, add a click event to document:

var fn=function(){
  alert("Hello, World!!");
};
bind(document,"click", fn);

Copy after login

Delete event binding unbind()

unbind() for the bind() function above

/************************************
* 删除事件绑定
* @param obj : 要删除事件的元素
* @param type : 事件名称。不加 "on". 如 : "click" 而不是 "onclick"
* @param fn : 事件处理函数
************************************/
function unbind( obj, type, fn ){
  if( obj.detachEvent){
    obj.detachEvent('on'+type, obj[type+fn]);
    obj[type+fn]=null;
  }else
    obj.removeEventListener( type, fn,false);
}

Copy after login

For example, delete the first bound document click event:

Copy code The code is as follows:
unbind(document,"click",fn);

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template