jQuery 事件 one() 方法



jQuery 事件one() 方法用於為選定的元素繫結一個或多個事件處理程式。它指定一個在事件發生時執行的函式。

此方法指定的事件處理程式函式對於每個元素僅執行一次。

語法

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

$(selector).one(event, data, handler)

引數

此方法接受三個名為“event”、“data”和“handler”的引數,如下所述:

  • event - 它指定一個或多個事件型別,用空格分隔,例如“click”、“dblclick”或自定義事件名稱。
  • data (可選) - 將附加資料傳遞給函式。
  • handler - 事件發生時要執行的函式。

返回值

此方法不返回值,但會為選定的元素繫結事件。

示例 1

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

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on this paragraph</p>
    <script>
        $('p').one("click", function(){
            $(this).css({"color": "green", "font-size": "20px"});
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個段落。當滑鼠指標單擊它時,文字的顏色和大小將發生變化:


當滑鼠指標單擊顯示的段落時:


示例 2

將多個事件附加到選定的元素。

以下是 jQuery 事件one() 方法的另一個示例。我們使用此方法將多個事件附加到選定的元素,即 <button>:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
        button{
            padding: 10px;
            width: 100px;color;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <p>Click or double-click on the submit button.</p>
    <button>Submit</button>
    <script>
        $('button').one({click: function(){
            $(this).css("background-color", "green");
            alert("The button was single-clicked.");
        }, dblclick: function(){
            $(this).css("background-color", "blue");
            alert("The button was double-clicked.");
        }});
    </script>
</body>
</html>

輸出

程式顯示一個按鈕,當單擊或雙擊它時,瀏覽器螢幕上會出現一個彈出警報,指示發生的事件型別:


示例 3

將 data 引數值傳遞給事件處理程式函式。

在下面的示例中,我們使用 jQuery one() 方法將事件處理程式繫結到

元素並在螢幕上顯示傳遞的資料值:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
        div{
            width: 150px;
            padding: 10px;
            background-color: green;
            color: white;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <p>Mouseenter on the below box to know the TP full form.</p>
    <div>TP</div>
    <script>
        $('div').one("mouseenter", {fullform: "TutorialsPoint"}, function(event){
            $('div').text(event.data.fullform);
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個 <div> 元素,其中包含文字“TP”。當滑鼠指標進入 'div' 元素時,"TP" 的完整形式將顯示在同一 <div> 元素中:


jquery_ref_events.htm
廣告

© . All rights reserved.