Javascript点击事件的3种写法(复习)

方法一:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点击</button>
</body>

<script>
    var btn = document.getElementById('btn')
    btn.onclick = function() {
    
    
        alert('点击事件')
    }

</script>

</html>

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点击</button>
</body>

<script>
    var btn = document.getElementById('btn')
    btn.addEventListener('click', function() {
    
    
        alert('点击事件')
    })

</script>

</html>

方法三

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="btn()">点击</button>
</body>

<script>
    function btn() {
    
    
        alert('点击事件')
    }
</script>

</html>

猜你喜欢

转载自blog.csdn.net/qq_52099965/article/details/127896097