如何使用 jQuery 多個事件觸發相同函式?


若要使用多個事件觸發同一函式,可將 jQuery on() 方法與多個事件結合使用,例如點選、雙擊、滑鼠進入、滑鼠離開、懸停等。

例項

你可嘗試執行以下程式碼,瞭解如何使用 jQuery 多個事件使用同一函式

即時演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").on({
   
        mouseenter: function(){
            $(this).css("background-color", "gray");
        },  
       
        mouseleave: function(){
            $(this).css("background-color", "red");
        },
       
        dblclick: function(){
            $(this).css("background-color", "yellow");
        }
       
    });
});
</script>
</head>
<body>

<p>Click, double click and move the mouse pointer.</p>

</body>
</html>

更新於: 2019 年 12 月 11 日

4K+ 觀看次數

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.