javascript - The difference between the definition of an event and whether it is a function
漂亮男人
漂亮男人 2017-06-26 10:56:00
0
2
667

<!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>
漂亮男人
漂亮男人

reply all(2)
女神的闺蜜爱上我

1. Firsth2[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 by alert('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!

h2[0].onclick = function(){
            alert('这是dom0级事件绑定方式');
        }
女神的闺蜜爱上我

The first line defines the attribute of the DOM element. The following access to DOM.onclick can be regarded as the access to the property.

<a id="test" onclick="alert('abc')">test</a>
<script>
var a = document.querySelector('#test');
console.log(a.onclick); // function onclick(event) { alert('abc'); }
a.attributes['onclick'].value = 'alert(\'test\')';
console.log(a.onclick); // function onclick(event) { alert('test'); }
</script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template