<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨游览器封装函数</title>
</head>
<body>
<h1 onclick="alert('这是html事件绑定方式1')">html事件绑定方式1</h1>
<h1 onclick="f1()">html事件绑定方式2</h1>
<h2 onclick="f1()">dom0级事件绑定方式</h2>
<script type="text/javascript">
function f1(){
alert('这是html事件绑定方式2');
}
var h2 = document.getElementsByTagName('h2');
console.log(h2[0]);
h2[0].onclick = function(){
alert('这是dom0级事件绑定方式');
}
h2[0].onclick = "alert('这是dom0级事件绑定方式')";
</script>
</body>
</html>
1. First
h2[0].onclick = "alert('This is the dom level 0 event binding method')"
; If you look at this writing carefully, you will know what it means! It is equivalent to treating"alert('This is the dom level 0 event binding method')"
as a string and assigning it to onclick. It is just a string and will not work!2. Then,
<h1 onclick="alert('This is html event binding method 1')">html event binding method 1</h1>
, this writing method is bound here in the html tag ,onclick
followed byalert('This is html event binding method 1')
, this part is the content of the function, which is what is executed when you click and trigger the event. This writing method is equivalent to<h1 onclick="(function(){alert('This is html event binding method 1')})()">html event binding method 1</h1>
, you will know what is going on after reading this way of writing! It is equivalent to defining an anonymous function that is automatically executed, and the content of the function execution is what you wrotealert('This is html event binding method 1')
.3. Finally, there is no need to explain this. The principle is that the event is triggered after clicking and the function is executed!
The first line defines the
attribute
of the DOM element. The following access to DOM.onclick can be regarded as the access to theproperty
.