jQuery click() 事件方法



jQuery 事件click()方法用於快速將點選處理程式附加到選定的元素。當click()方法在元素上呼叫時,它要麼觸發點選事件,要麼(如果提供了函式)將該函式附加到點選事件發生時執行。

語法

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

$(selector).click(function)

引數

此方法接受一個可選引數“function”,如下所述:

  • function (可選) - 一個可選引數,指定點選事件發生時要執行的函式。

返回值

此方法將點選處理程式附加到選定的元素,但不返回值。

示例 1

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

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Click on the below button to see a pop-up alert message.</p>
    <button>Click me!</button>
    <script>
        $('button').click(function(){
            alert("You clicked on button");
        });
    </script>
</body>
</html>

輸出

執行上述程式後,瀏覽器螢幕上將顯示一個按鈕。如果使用者點選該按鈕,將觸發一個彈出警報:

 

示例 2

在以下示例中,我們使用 jQuery click()方法將點選處理程式附加到指定的 div 元素。當用戶點選“div”元素時,瀏覽器螢幕上將顯示一個彈出警報訊息:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <div>Click on me!</div>
    <span></span>
    <script>
        $('div').click(function(){
            alert("You clicked on div element.");
        });
    </script>
</body>
</html>

輸出

在上述程式中,當用戶點選顯示的訊息時,瀏覽器螢幕上將出現一個彈出警報:

 

示例 3

在下面的示例中,我們使用 jQuery click()方法將點選處理程式附加到button元素。當點選按鈕時,一條訊息將出現在它旁邊:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Click on the below button to print some message</p>
    <button>Click me!</button>
    <span></span>
    <script>
        $('button').click(function(){
            document.querySelector('span').innerHTML = "Welcome to TutorialsPoint....!";
        });
    </script>
</body>
</html>

輸出

點選按鈕前:

 

點選按鈕後:

 
jquery_ref_events.htm
廣告

© . All rights reserved.