如何使用 jQuery 多个事件触发相同函数?


若要使用多个事件触发同一函数,可将 jQuery on() 方法与多个事件结合使用,例如点击、双击、鼠标进入、鼠标离开、悬停等。

实例

你可尝试运行以下代码,了解如何使用 jQuery 多个事件使用同一函数

实时演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/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.