Home > Web Front-end > JS Tutorial > There are several ways to add events to elements in javascript

There are several ways to add events to elements in javascript

醉折花枝作酒筹
Release: 2021-06-15 09:15:10
Original
3129 people have browsed it

Javascript has three ways to add events to elements, namely: 1. Binding directly in the html tag; 2. Binding after obtaining the corresponding dom element in js; 3. Using addEventListener in js to implement binding Certainly.

There are several ways to add events to elements in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. Bind directly in the html tag;

2. Obtain the corresponding dom element in js and bind it;

3. Use addEventListener in js () to implement binding;

The specific code examples are as follows:

<!-- 以下为给dom元素绑定js事件的三种方法 -->

    <!-- 1--html内直接绑定 -->
    <input type="button" id="btn0" onclick="alert(&#39;执行了html绑定的方法&#39;)" value="html中绑定"></input>
    <!-- 2--使用js绑定 -->
    <input type="button" id="btn1" value="js绑定">
    <!-- 3--使用addEventListener绑定 -->
    <input type="button" id="btn2" value="addEventListener绑定"></input>

    <script>
        //********js绑定事件的js代码*********
        let button1 = document.getElementById("btn1")
        button1.onclick = function() { console.log("执行了js绑定的事件") }
        //将覆盖之前绑定的onclick事件
        button1.onclick = function() { console.log("执行了js绑定的第二个事件") }


        //*********addEventListener绑定的js代码*********
        let button2 = document.getElementById("btn2")
        //使用addEventListener()可为一个元素绑定多个事件
        button2.addEventListener("mouseover", func1, false)
        button2.addEventListener("click", func2, false)
        button2.addEventListener("click", func3, false)
        function func1() {
            console.log(button2)
        }
        function func2() {
            console.log(Date())
        }
        function func3() {
            console.log("---------------")
        }
        //使用removeEventListener(event,function)移除事件
        // button2.removeEventListener("mouseover", func1)
    </script>
Copy after login

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of There are several ways to add events to elements in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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