1. 程式人生 > 其它 >jQuery: 事件註冊 on()

jQuery: 事件註冊 on()

技術標籤:jQueryjquery

目錄




on() 統一了事件註冊的方式

1. on() 註冊簡單事件


由元素自己觸發,不支援動態繫結。

關於動態繫結,請參考 [未來存在的元素,事件監聽](https://blog.csdn.net/weixin_46618182/article/details/110886572)

<style>
    .mydiv {
        width: 100px;
        height: 100px;
        background-color: #4d90fe;
    }
</style> <div class="mydiv"></div> <script> $(".mydiv").on("click", function () { console.log("div的點選事件..."); }); </script>

點選 div 時,觸發點選事件:



2. on() 註冊委託事件


由目標元素的父元素觸發,支援動態繫結。

關於動態繫結,請參考 [未來存在的元素,事件監聽](https://blog.csdn.net/weixin_46618182/article/details/110886572)

<style>
    .father {
        width: 200px;
        height: 200px;
        background-color: #4d90fe;
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: #ffc700;
    }
</style>

<div class="father">
    <div class="son"></div>
</div> <script> $(".father").on("click", ".son", function () { console.log("son的點選事件..."); }); </script>

點選子元素時,觸發點選事件: