怎样创建并触发一个事件

1. 创建事件: document.createEvent();

2. 触发事件: document.dispatchEvent();

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id="butt">Click</button>
    <script>
        // 创建一个Event实例对象
        var event = document.createEvent('Event');

        // 初始化事件信息
        event.initEvent('build', true, true);

        // 添加事件监听函数
        document.addEventListener('build', function (e) {
            console.log(e.type); // "build"
        }, false);

        // 触发事件
        document.dispatchEvent(event);
    </script>
</body>

</html>

 

posted on 2019-09-19 09:13  aisowe  阅读(465)  评论(0编辑  收藏  举报

导航