js自定义事件的三种方式

本文介绍了JavaScript中创建自定义事件的三种方式:Event方式、CustomEvent方式以及兼容IE的自定义事件。通过示例代码展示了如何为按钮添加自定义事件监听和触发,以实现不同类型的事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button type="button" name="button" class="test" id="btn1">Event方式自定义事件</button>
    <button type="button" name="button" class="test" id="btn2">CustomEvent方式自定义事件</button>
    <button type="button" name="button" class="test" id="btn3">兼容IE的自定义事件</button>
</body>
<script>
    方式一:浏览器都兼容的性质,但是目前官网不建议用;
    var button3 = document.getElementById('btn3');
    var create = document.createEvent('Event');
    create.initEvent('create',false, false);
    document.addEventListener('create',function (e) {
        alert('兼容IE的自定义事件顺利触发')
    });
    button3.addEventListener('click',function () {
        document.dispatchEvent(create)
    });
   方式二:使用Event类自定义事件
    var button = document.getElementById('btn1');
    var selfEvent = new Event('self',{
        "bubbles": true,//事件是否冒泡
        "cancelable": false,//事件是否支持取消
        "composed": false//事件是否在阴影根之外
    });
    //监听
    document.addEventListener('self',function (e) {
        alert('Event自定义事件被顺利触发')
    });
    //触发
    button.addEventListener('click',function () {
        document.dispatchEvent(selfEvent)
    });
   方式三:使用CustomEvent类自定义事件
    var button2 = document.getElementById('btn2');
    var custom = new CustomEvent('custom',{
        detail:{
            age: 18
        },//detail对象是比旭要有的
        "bubbles": true,
        "cancelable": false
    });
    document.addEventListener('custom',function () {
        alert('CustomEvent自定义事件被顺利触发')
    });
    button2.addEventListener('click',function () {
        document.dispatchEvent(custom)
    });

</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值