如何使用 jQuery 對 DOM 元素繫結所有事件?


bind( type, [data], fn ) 方法為每個匹配元素繫結到一個或多個事件(如單擊)。它還可以繫結自定義事件。

可能的事件值 − blur、focus、load、resize、scroll、unload、click 等。

以下是此方法使用的所有引數的說明 −

  • type − 一個或多個以空格分隔的事件型別。
  • data − 這是可選引數,表示作為 event.data 傳遞給事件處理程式的其他資料。
  • fn − 在匹配元素集中的每個元素上繫結到事件的函式。

示例

你可以嘗試執行以下程式碼以瞭解如何對 DOM 元素繫結所有事件

即時演示

<html>

   <head>
      <title>jQuery bind()</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $('div').bind('click', function(event){
               alert('Hi there!');
            });
         });
      </script>
       
      <style>
         .div {
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
   
</html>

更新於:2019 年 12 月 11 日

606 次瀏覽

開始您職業生涯

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.