jQuery 中的事件方法是什麼?


常用事件方法包括 $(document).ready()、click()、dblclick() 等。有一些方法可以在事件物件中呼叫,

以下是可以用於事件物件的一些方法,

序號
方法及說明
1
preventDefault() 
防止瀏覽器執行預設操作。
2
isDefaultPrevented() 
返回是否已在該事件物件上呼叫過 event.preventDefault()。
3
isPropagationStopped() 
返回是否已在該事件物件上呼叫過 event.stopPropagation()。
4
stopImmediatePropagation() 
停止執行其他處理程式。


讓我們來看一下 stopPropagation() 方法的一個示例。stopPropagation() 方法停止將事件冒泡到父元素,從而阻止通知任何父處理程式該事件。

示例

你可以嘗試執行以下程式碼,瞭解如何在 jQuery 中使用事件方法 stopPropagation() −

線上演示

<html>

   <head>
      <title>jQuery stopPropagation() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function(event){
               alert("This is : " + $(this).text());
               // Comment the following to see the difference
               event.stopPropagation();
            });
         });
      </script>
       
      <style>
         div {
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:160px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any box to see the effect:</p>
       
      <div id = "div1" style = "background-color:blue;">
         OUTER BOX
         <div id = "div2" style = "background-color:red;">
            INNER BOX
         </div>
      </div>
       
   </body>
</html>

更新於: 2020 年 2 月 14 日

168 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.