jQuery 学习笔记(三)

1.jQuery 事件注册

jQuery 为我们提供了方便的事件注册机制,使开发人员易于操作,优缺点如下:

  • 优点:操作简单,且不用担心事件覆盖等问题。
  • 缺点:普通的事件注册不能做事件委托,且无法实现事件绑定,需要借助其它方法。
    在这里插入图片描述

演示代码:

<body>
    <div></div>
    <script>
        $(function() {
            // 1. 单个事件注册
            $("div").click(function() {
                $(this).css("background", "purple");
            });
            $("div").mouseenter(function() {
                $(this).css("background", "skyblue");
            });
        })
    </script>
</body>

2.jQuery 事件处理

因为普通注册事件方法的不足,jQuery 又开发了多个处理方法,重点讲解如下:

  • on():用于事件绑定,也是目前最好用的事件绑定方法
  • off():事件解绑
  • trigger() / triggerHandler():事件触发。

2.1 事件处理 on() 绑定事件

因为普通注册事件方法不足,jQuery 又创建了多个新的事件绑定方法 bind() / live() / delegate() / on() 等,其中最好用的是 on()。
在这里插入图片描述
演示代码:

<style>
    div{
        width: 100px;
        height: 100px;
        background-color: pink;
    }

    .current {
        background-color: purple;
    }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div></div>
<script>
    $(function() {
        // 1.单个事件注册
        // $("div").click(function() {
        //     $(this).css("background", "purple");
        // })
        
        // $("div").mouseenter(function() {
        //     $(this).css("background", "skyblue");
        // })

        // 2.事件处理 on
        // (1) 使用 on 绑定多个事件
        // $("div").on({
        //     mouseenter: function() {
        //         $(this).css("background", "skyblue");
        //     },
        //     click: function() {
        //         $(this).css("background", "purple");
        //     },
        //     mouseleave: function() {
        //         $(this).css("background", "blue");
        //     }
        // })
        $("div").on("mouseenter mouseleave", function() {
            $(this).toggleClass("current");
        })
    })
</script>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值