Bind and clear events, internal environment

The first way to bind

ele.on event type  = function() {}

Compatibility is good, but only one handler can be bound to the same event on the same element.

Can also be written between HTML lines.

write in script

<body>

<div id="demo" style="width: 100px;height: 100px;background-color: blue;">

</div>

<script type="text/javascript">

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

div.onclick = function () {
	
div.style.backgroundColor = 'red';
	
}

</script>

Written in inline HTML

<body>

<div id="demo" style="width: 100px;height: 100px;background-color: blue;"
 onclick="div.style.backgroundColor = 'red';">

</div>

<script type="text/javascript">

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

</script>
</body>

Method to clear the event: ele.on event type = null or false


The second way of binding

ele.addEventListener (event type, handler, false)

Multiple handlers can be bound to the same event for the same element

Not compatible with IE9 and below

Notice:

The event is in the form of a string, no need to write on

Cannot bind the same handler function! !

<body>

<div id="demo" style="width: 100px;height: 100px;background-color: blue;">

</div>

<script type="text/javascript">

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

div.addEventListener('click',test,false);

function test() {
	
div.style.backgroundColor = 'yellow';
	
}

</script>

</body>

Methods to clear events:

ele.removeEventListener (event type, handler, false),

The handler function cannot be an anonymous function, otherwise it cannot be cleared.


The third binding method (IE unique)

ele.attachEvent('on' + event type, handler)

Test ie8 can be used, high version ie does not support


Methods to clear events:

ele.detachEvent("on" + event type, handler),

The handler function cannot be an anonymous function, otherwise it cannot be cleared.


The runtime environment of the event handler

ele.on event = function() {}

<body>

<div style="width: 100px;height: 100px;background: red;"></div>

<script type="text/javascript">
	
var div = document.getElementsByTagName('div')[0];
	
div.onclick = function () {
	
console.log(this)
	
}
	
</script>

</body>

program this points to the dom element itself

QQ浏览器截图_20180327112730_6B2A63D70B164f6281F35727D0D3A130.jpg


ele.addEventListenner

program this points to the dom element itself


div.attachEvent('onlick',test)

program this points to window


Encapsulates a method compatible with all browser element binding events

	function addEle(ele,type,fu) {
	
		if(ele.addEventListener) {
		
			ele.addEventListener(type,fu,false);
		
		}else if(ele.attachEvent){
		
			ele.attachEvent('on' + type, function () {
			
			fu.call(ele);
			
			})
		
		}else{
		
		ele['on' + type] = fu;
		
		}
	
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326043519&siteId=291194637