jQuery 事件 delegate() 方法



jQuery 事件delegate() 方法用於將一個或多個事件處理程式附加到指定元素的子元素,並指定一個函式在事件發生時執行(執行)。

此外,此方法將事件處理委託給一個父元素,該父元素偵聽其子元素(由選擇器指定)上的事件。

jQuery 3.0 版中的 delegate() 方法已棄用,因此請使用 on() 方法代替 delegate() 方法。

語法

以下是 jQuery 事件delegate() 方法的語法:

$(selector).delegate(childSelector, event, data, function)

引數

此方法接受四個引數,分別命名為“childSelector”、“event”、“data”和“function”,如下所述:

  • childSelector - 將觸發元素的子元素的選擇器。
  • event - 一個或多個事件型別,例如:“click”或“keyup”。
  • data - 可選資料,用於傳遞事件處理程式。
  • function - 事件觸發時要執行(執行)的函式。

返回值

此方法不返回值,但它將一個或多個事件處理程式附加到選定的元素。

示例 1

以下程式演示了 jQuery 事件delegate() 方法的用法:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
      <style>
        .demo{
            background-color: aqua;
            width: 250px;
            color: white;
        }
        p{
            width: 250px;
        }
      </style>
    </head>
<body>
    <div class="demo">
        <p>Click me! to change background color</p>
    </div>
    <p>Tutorialspoint</p>
    <script>
        $('div').delegate('p', 'click', function(){
            $('p').css("background-color", "red");
        });
    </script>
</body>
</html>

輸出

上述程式顯示了兩條訊息,當用戶單擊第一條(父)訊息時,兩條訊息(父和子)的背景顏色將變為紅色:

 

當用戶單擊顯示的訊息(父)時:

示例 2

以下是 jQuery 事件delegate() 方法的另一個示例。在這裡,我們使用此方法與 table 元素一起,在使用者單擊時切換 table 內 td 元素的類:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
      <style>
        .demo{
            background-color: gray;
            color: white;
            text-align: center;
        }
      </style>
    </head>
<body>
    <p>Click on the table data (td) element to toggle class.</p>
    <table>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <tr>
            <td>Rahul Verma</td>
            <td>rahul123@gmail.com</td>
        </tr>
    </table>
    <script>
        $('table').delegate('td', 'click', function(){
            $(this).toggleClass('demo');
        });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個包含一些表格資料的表格,當用戶單擊表格資料元素時,它將在“demo”類之間切換:

 

當用戶單擊顯示的表格資料時,背景將更改:

 

示例 3

使用多個事件

正如我們所討論的,jQuery 事件delegate() 方法可以透過在同一字串中以空格分隔的列表形式指定它們來處理多個事件:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
      <style>
        .demo{
            background-color: aquamarine;
            width: 200px;
        }
      </style>
    </head>
<body>
    <p>Click, mouseover, or mouseout on the below element to toggle the class.</p>
    <div>
        <p>Hello World</p>
    </div>
    <script>
        $('div').delegate('p', 'click mouseover mouseout', function(){
            $(this).toggleClass('demo');
        });
    </script>
</body>
</html>

輸出

上述程式在使用者執行列出的事件(例如:單擊、滑鼠懸停或滑鼠移出操作)時顯示一條訊息。在這些操作期間,將向觸發事件的元素新增 .demo 類,並在事件不再活動時將其刪除:

 
jquery_ref_events.htm
廣告