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


JQuery click()用法及代碼示例


jQuery click()是一個內置方法,用於啟動單擊事件或附加一個在單擊事件發生時運行的函數。

用法:

$(selector).click(function);

參數:

它接受一個可選參數“function”,用於在單擊事件發生時運行。

jQuery 示例展示 click() 方法的用法原理:

示例 1:在下麵的代碼中,沒有函數傳遞給此方法。

HTML


<!DOCTYPE html>
<html>
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("p").click();
        });
    </script>
    <style>
        p {
            display: block;
            width: 300px;
            padding: 20px;
            font-size: 30px;
            border: 2px solid green;
        }
    </style>
</head>
<body>
    <!-- click on this method -->
    <p onclick="alert('paragraph was clicked')">
        This is a paragraph.
    </p>
</body>
</html>

輸出:

示例 2:在下麵的代碼中,函數被傳遞給此方法。

HTML


<!DOCTYPE html>
<html>
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        // jQuery code to show the working of this method
        $(document).ready(function () {
            $("p").click(function () {
                $(this).fadeOut();
            });
        });
    </script>
    <style>
        p {
            display: block;
            width: 370px;
            padding: 25px;
            font-size: 25px;
            border: 2px solid green;
        }
    </style>
</head>
<body>
    <!-- click on this paragraph and 
        the paragraph will disappear -->
    <p>Click inside this block and
        whole block will disappear !!!
    </p>
</body>
</html>

輸出:



相關用法


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