Home Web Front-end JS Tutorial JavaScript event binding learning points_basic knowledge

JavaScript event binding learning points_basic knowledge

May 16, 2016 pm 03:11 PM

Event binding is divided into two types: one is traditional event binding (inline model, script model), and the other is modern event binding (DOM2-level model). Modern event binding provides more powerful and convenient functions over traditional binding.

1 Problems with traditional event binding

The inline model in traditional event binding will not be discussed and is rarely used. Let's take a look at the script model first. The script model assigns a function to an event handling function. Traditional binding such as:

1

2

3

4

5

6

window.onload=function(){

 var box=document.getElementById('box');

 box.onclick = function(){

  alert('Lee');

 };

};

Copy after login

Problem 1: An event handling function triggers two events

If a page has two or more js, and the first js is developed by the first programmer, the second js is developed by the second programmer. The first window.onload is overwritten, such as

1

2

3

4

5

6

7

window.onload=function(){

 alert('Lee');

};

 

window.onload=function(){

 alert('Mr.lee');

}

Copy after login

The result just printed Mr.lee

In fact, there are ways to solve this problem. Take a look at the following two forms.
a:

1

2

3

4

5

6

7

8

9

10

11

alert(window.onload);//一开始没有注册window.onload,那么就是null

 

window.onload=function(){

 alert('Lee');

};

 

alert(window.onload);//如果已经有window.onload,打印的是函数function

 

window.onload=function(){

 alert('Mr.lee');

}

Copy after login

b:

1

2

3

4

5

6

7

8

9

10

11

alert(typeof window.onload);//一开始没有window.onolad,旧版火狐显示undefined,新版显示object,

 

window.onload=function(){

 alert('Lee');

};

 

alert(typeof window.onload);//如果已经有window.onload,所有浏览器都会显示function

 

window.onload=function(){

 alert('Mr.lee');

}

Copy after login

So there is a solution.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

window.onload=function(){

 alert('Lee');

};

 

if(typeof window.onload=='function'){

 var saved=null;//保存上一个事件对象

 saved=window.onload;

}

 

//saved 就是window.onload,saved()相当于window.onload(),但是window.onload()不能执行的

//所以saved()相当于window.onload=function(){}

 

window.onload=function(){

 if(saved){

  saved();//执行上一个事件 window.onload=function(){}

 }

 alert('Mr.lee'); //执行本事件

}

Copy after login

Question 2: Event Switcher
Switch a div with the ID of box, let the background red and blue inside switch directly, and pop up the box once before switching, such as:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

window.onload=function(){

 var box=document.getElementById('box');

 box.className="red";

 box.onclick=function(){

  alert('Lee'); //只执行了一次

  blue.call(this);//通过匿名函数执行某一函数,那么里面的this就是代表的window,所以可以通过call传递

 };

}

 

function blue(){

 this.className="blue";

 this.onclick=red;

  

}

 

function red(){

 this.className="red";

 this.onclick=blue;

}

Copy after login

Although the above code implements the switching function, the pop-up box is only executed once.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

//添加事件函数

//obj相当于window

//type相当于onload

//fn相当于function(){}

function addEvent(obj,type,fn){

 //用于保存上一个事件

 var saved=null;

 if(typeof obj['on'+type]=='function'){

  saved=obj['on'+type];//保存上一个事件

 }

 obj['on'+type]=function(){

  if(saved){

   saved();

  }

  fn.call(this);

 }

  

}

addEvent(window,'load',function(){

 var box=document.getElementById("box");

 //addEvent(box,'click',function(){ //目的达到,每次都执行了,没有被覆盖

 // alert('ss');

 //});

 addEvent(box,'click',blue);

});

 

function red(){

 this.className="red";

 addEvent(box,'click',blue);

}

 

function blue(){

 this.className="blue";

 addEvent(box,'click',red);

}

 

//当不停的切换的时候,浏览器突然卡死,并且报错:too much recursion,太多的递归

//因为积累了太多的保存的事件

//解决方案,就是用完的事件,就立刻移除掉

Copy after login

According to the above code, an error occurred in the comment. The solution is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

//添加事件函数

//obj相当于window

//type相当于onload

//fn相当于function(){}

function addEvent(obj,type,fn){

 //用于保存上一个事件

 var saved=null;

 if(typeof obj['on'+type]=='function'){

  saved=obj['on'+type];//保存上一个事件

 }

 obj['on'+type]=function(){

  if(saved){

   saved();

  }

  fn.call(this);

 }

  

}

 

 

//当不停的切换的时候,浏览器突然卡死,并且报错:too much recursion,太多的递归

//因为积累了太多的保存的事件

//解决方案,就是用完的事件,就立刻移除掉

 

 

//移除事件函数

function removeEvent(obj,type){

 if(obj['on'+type]){

  obj['on'+type]=null;

 }

}

 

 

addEvent(window,'load',function(){

 var box=document.getElementById("box");

 //addEvent(box,'click',function(){ //目的达到,每次都执行了,没有被覆盖

 // alert('ss');

 //});

 addEvent(box,'click',blue);

});

 

function red(){

 this.className="red";

 removeEvent(this,'click');

 addEvent(box,'click',blue);

}

 

function blue(){

 this.className="blue";

 removeEvent(this,'click');

 addEvent(box,'click',red);

}

Copy after login

Two W3C event handling functions
addEventListener() and removeEventListener()
There are two W3C event handling functions, addEventListener() and removeEventListener().

//W3C comes with two add events and deletion events
1. Coverage problem, solved

1

2

3

4

5

6

7

8

9

10

11

window.addEventListener('load',function(){

 alert('Lee');

},false);

 

window.addEventListener('load',function(){

 alert('Mr.Lee');

},false);

 

window.addEventListener('load',function(){

 alert('Mrs.Lee');

},false);

Copy after login

2. The problem of blocking the same function is solved

1

2

3

4

5

6

window.addEventListener('load',init,false);

window.addEventListener('load',init,false);

window.addEventListener('load',init,false);

function init(){

 alert('Lee');

}

Copy after login

3. Is it possible to pass this and solve it
Example 1:

1

2

3

4

5

6

window.addEventListener('load',function(){

 var box=document.getElementById('box');

 box.addEventListener('click',function(){

  alert(this);

 },false);

},false);

Copy after login

Example 2:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

window.addEventListener('load',function(){

 var box=document.getElementById('box');

 box.addEventListener('click',blue,false);

},false);

 

function red(){

 this.className="red";

 this.removeEventListener('click',red,false);

 this.addEventListener('click',blue,false);

}

 

function blue(){

 this.className="blue";

 this.removeEventListener('click',blue,false);

 this.addEventListener('click',red,false);

}

Copy after login

4. Add an additional method. Will it be overwritten or can only be executed once? Solve

1

2

3

4

5

6

7

window.addEventListener('load',function(){

 var box=document.getElementById('box');

 box.addEventListener('click',function(){

  alert('Lee');

 },false);

 box.addEventListener('click',blue,false);

},false);

Copy after login

To sum up: W3C has solved these problems perfectly and is very easy to use. However, IE8 and previous browsers do not support it. Instead, they use their own events. Of course, IE9 has fully supported this of W3C. Two event handling functions.

W3C can set bubbling and capturing methods.

Browsers that support the W3C standard use the addEventListener(event,fn,useCapture) method when adding events. The third parameter useCapture in the base is a Boolean value, which is used to set whether the event is executed during event capture or when the event occurs. Executed when soaking. Browsers that are not compatible with W3C (IE) use the attachEvent() method. This method has no relevant settings. However, IE's event model is executed by default when the event bubbles up, that is, when useCapture is equal to false, so put it in It is safer to set useCapture to false when handling events, and it also achieves browser compatibility.

Event capture phase: The event starts from the top level label and searches downward until the event target (target) is captured.
Event bubbling stage: The event starts from the event target (target) and bubbles up to the top-level label of the page.
The spread of events can be stopped:
In W3c, use the stopPropagation() method
Set cancelBubble = true under IE;

3. IE event handling function

attachEvent() and detachEvent()
IE implements two methods similar to those in DOM: attachEvent() and detachEvent(). Both methods accept the same parameters: event name and function.

When using these two sets of functions, let’s first talk about the differences: 1. IE does not support capturing, only bubbling; 2. IE adding events cannot block duplicate functions; 3. this in IE points to window instead of a DOM object. 4. In traditional events, IE cannot accept event objects, but using attchEvent can, but there are some differences.

1. The coverage problem is solved, but there are differences. The result is Mrs.Lee, Mr.Lee, and finally Lee

1

2

3

4

5

6

7

8

9

10

window.attachEvent('onload',function(){

 alert('Lee');

});

 

window.attachEvent('onload',function(){

 alert('Mr.Lee');

});

window.attachEvent('onload',function(){

 alert('Mrs.Lee');

});

Copy after login

2. The problem of blocking the same function has not been solved.

1

2

3

4

5

6

window.attachEvent('onload',init);

window.attachEvent('onload',init);

 

function init(){

 alert('Lee');

}

Copy after login

3. Can this be passed? No, this refers to window. Need to use call method.

1

2

3

4

5

6

7

window.attachEvent('onload',function(){

 var box=document.getElementById('box');

 box.attachEvent('onclick',function(){

  //alert(this===box);

  alert(this===window); //true

 });

});

Copy after login

The next way is to pass window.event.srcElement. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

window.attachEvent('onload',function(){

 var box=document.getElementById('box');

 box.attachEvent('onclick',blue);

});

 

function red(){

 var that=window.event.srcElement;

 that.className="red";

 that.detachEvent('onclick',red);

 that.attachEvent('onclick',blue);

}

 

function blue(){

 var that=window.event.srcElement;

 that.className="blue";

 that.detachEvent('onclick',blue);

 that.attachEvent('onclick',red);

}

Copy after login

4. Add an additional method. Will it be overwritten or can only be executed once? Solve it.

In traditional binding, IE cannot accept event objects through parameter passing like W3C, but it can be done using attachEvent().

1

2

3

4

5

6

7

8

9

10

11

12

window.attachEvent('onload',function(){

 var box=document.getElementById('box');

 box.onclick=function(evt){ //传统方法IE无法通过参数获取evt

  alert(evt);//undefined

 }

 box.attachEvent('onclick',function(evt){

  alert(evt);//object

  alert(evt.type);//click

  alert(evt.srcElement.tagName);//DIV

  alert(window.event.srcElement.tagName);//DIV

 });

});

Copy after login

Cross-browser compatibility

Cross-browser events

1

2

3

4

5

6

7

function addEvent(obj,type,fn){

 if(obj.addEventListener){

  obj.addEventListener(type,fn,false);

 }else if(obj.attachEvent){

  obj.attachEvent('on'+type,fn);

 }

}

Copy after login

Cross browser removal event

1

2

3

4

5

6

7

function removeEvent(obj,type,fn){

 if(obj.removeEventListener){

  obj.removeEventListener(type,fn,false);

 }else if(obj.detachEvent){

  obj.detachEvent('on'+type,fn);

 }

}

Copy after login

Get target object across browsers

1

2

3

4

5

6

7

function getTarget(evt){

 if(evt.target){

  return evt.target;

 }else if(window.event.srcElement){

  return window.event.srcElement;

 }

}

Copy after login

调用方式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

addEvent(window,'load',function(){

 var box=document.getElementById('box');

 addEvent(box,'click',blue);

});

 

 

function red(evt){

 var that=getTarget(evt);

 that.className="red";

 removeEvent(that,'click',red);

 addEvent(that,'click',blue);

}

 

function blue(evt){

 var that=getTarget(evt);

 that.className="blue";

 removeEvent(that,'click',blue);

 addEvent(that,'click',red);

}

Copy after login

四.事件对象的其他补充

relatedTarget事件

w3c中的一个relatedTarget事件。
例如:

1

2

3

4

5

6

7

8

9

10

addEvent(window,'load',function(){

 var box=document.getElementById('box');

 addEvent(box,'mouseover',function(evt){

  alert(evt.relatedTarget); //得到移入box最近的那个DOM对象

 });

  

 addEvent(box,'mouseout',function(evt){

  alert(evt.relatedTarget); //从box移出最近的那个DOM对象

 });

});

Copy after login

IE提供了两组分别用于移入移出的属性fromElement和toElement,分别对应mouseover和mouseout。

1

2

3

4

5

6

7

8

9

10

addEvent(window,'load',function(){

 var box=document.getElementById('box');

 addEvent(box,'mouseover',function(){

  alert(window.event.fromElement.tagName); //得到移入box最近的那个DOM对象

 });

  

 addEvent(box,'mouseout',function(){

  alert(window.event.toElement.tagName); //从box移出最近的那个DOM对象

 });

});

Copy after login

PS:fromElement和toElement如果分别对应相反的鼠标事件,没有任何意义。

剩下要做的就是跨浏览器兼容操作:

1

2

3

4

5

6

7

8

9

10

11

12

function getTarget(evt){

 var e=evt || window.event;

 if(e.srcElment){ //IE

  if(e.type=='mouseover'){

   return e.fromElement.tagName;

  }else if(e.type="mouseout"){

   return e.toElement.tagName;

  }

 }else if(e.relatedTarget){ //w3c

  return e.relatedTarget;

 }

}

Copy after login

屏蔽跳转操作

取消事件的默认行为有一种不规范的做法,就是返回false。

1

2

3

4

link.onclick=function(){

 alert('Lee');

 return false;

}

Copy after login

PS:虽然return false;可以实现这个功能,但是有漏洞。
第一:必须写到最后,这样导致中奖的代码执行后,有可能执行不到return false;
第二:return false 写到最前那么之后的自定义操作就失效了。
所以最好的办法应该是在最前面就阻止默认行为,并且后面的代码还可以执行。

1

2

3

4

5

6

7

8

9

link.onclick=function(evt){

 evt.preventDefault;//w3c,阻止默认行为

 alert('Lee');

}

 

link.onclick=function(evt){

 window.event.returnValue=false;//IE,阻止默认行为

 alert('Lee');

}

Copy after login

那么跨浏览器的兼容:

1

2

3

4

5

6

7

8

function preDef(evt){

 var e=evt || window.event;

 if(e.preventDefault){

  e.preventDefault();

 }else{

  e.returnValue=false;

 }

}

Copy after login

右键菜单contextmenu
兼容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

function preDef(evt){

 var e=evt || window.event;

 if(e.preventDefault){

  e.preventDefault();

 }else{

  e.returnValue=false;

 }

}

 

addEvent(window,"load",function(){

 var body=document.getElementsByTagName('body')[0];

 addEvent(body,'contextmenu',function(evt){

  preDef(evt);

 })

});

Copy after login

PS:contextmenu事件很常用,这直接导致浏览器兼容性较为稳定。

卸载前事件:beforeunload
这个事件可以帮助在离开本页的时候给出相应的提示,“离开”或者“返回”操作。

1

2

3

addEvent(window,'beforeonload',function(){

 preDef(evt);

});

Copy after login

鼠标滚轮(mousewheel)和DOMMouseScroll
用于获取鼠标上下滚轮的距离

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

addEvent(document,'mousewheel',function(evt){ //非火狐

 alert(getWD(evt));

});

 

addEvent(document,'DOMMouseScroll',function(evt){ //火狐

 alert(getWD(evt));

});

 

function getWD(evt){

 var e=evt|| window.event;

 if(e.wheelDelta){

  return e.wheelDelta;

 }else if(e.detail){ //火狐

  return -evt.detail*30;

 }

}

Copy after login

PS:通过浏览器检测可以确定火狐只执行DOMMouseScroll。

DOMContentLoaded事件和readystatechange事件

DOMContentLoaded事件和readystatechange事件,有关DOM加载方面的事件。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles