當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JQuery event.isDefaultPrevented()用法及代碼示例


isDefaultPrevented()方法是jQuery中的內置方法,它檢查是否為事件調用了preventDefault()方法。此方法返回一個布爾值。如果在事件上調用preventDefault(),則返回True,否則返回False。

用法:

event.isDefaultPrevented()

參數:它接受來自事件綁定函數的單個參數事件。


返回值:如果在事件上調用了preventDefault()函數,則返回True,否則返回false。

示例1:本示例檢查是否在事件上調用isPreventDefault()方法。

<!doctype html> 
<html> 
      
<head> 
    <title> 
        isPreventDefault() Method 
    </title> 
      
    <script src= 
        "https://code.jquery.com/jquery-3.3.1.min.js"> 
    </script> 
</head> 
  
<body> 
    <a href="https://www.geeksforgeeks.org"> 
        Go to Homepage 
    </a> 
      
    <div id="initial"></div> 
    <div id="prevented"></div> 
    <div id="response"></div> 
      
    <!-- Script to check preventDefault() Method called or not -->
    <script> 
        $( "a" ).click(function( event ) { 
              
            $( "#initial" ).html( "Before: isDefaultPrevented? <strong>" 
                    +event.isDefaultPrevented()+"</strong>"); 
                      
            event.preventDefault(); 
              
            $( "#prevented" ).html( "preventDefault() is called now."); 
              
            $( "#response" ).html( "So, you are not going anywhere." 
                    + " isDefaultPrevented? <strong>" 
                    + event.isDefaultPrevented() + "</strong>"); 
        }); 
    </script> 
</body> 
  
</html>                    

輸出:
之前單擊鏈接:
Initial stage of page
單擊鏈接後:
After clicking on the link

注意:粗體字(是/否)是isDefaultPrevented()方法的值。

示例2:本示例檢查isDefaultPrevented()方法是否阻止默認操作。

<!doctype html> 
<html> 
      
<head> 
    <title> 
        isPreventDefault() Method 
    </title> 
    <script src= 
        "https://code.jquery.com/jquery-3.3.1.min.js"> 
    </script> 
</head> 
  
<body> 
  
    <form action = "action.php"> 
        Input:<br> 
        <input type="text" name="input_1"> 
          
        <button type="submit">Submit</button> 
          
    </form>  
      
    <!-- Script to describe isDefaultPrevented() Method -->
    <script> 
        $( "button" ).click(function( event ) { 
            if(event.isDefaultPrevented()) 
                alert('Default action was prevented'); 
            else 
                alert('Click Ok'); 
          
            event.preventDefault(); 
          
            if(event.isDefaultPrevented()) 
                alert('Default action was prevented'); 
            else 
                alert('Click Ok'); 
        }); 
    </script> 
</body> 
  
</html>                    

輸出:
之前單擊提交按鈕:

單擊提交按鈕後:

完成上述步驟後,將阻止默認事件:



相關用法


注:本文由純淨天空篩選整理自Vyshnav S Deepak大神的英文原創作品 jQuery | event.isDefaultPrevented() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。