如何使用 jQuery 绑定 DOM 元素上的所有事件?

jqueryweb developmentfront end technology更新于 2026/1/29 20:37:17

bind( type, [data], fn ) 方法为每个匹配元素绑定一个处理程序到一个或多个事件(例如 click)。它也可以绑定自定义事件。

可能的事件值 − 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>

相关文章