jQuery中事件的绑定和解绑以及事件冒泡和事件冒泡的阻止

本文详细介绍了jQuery中元素事件的绑定,包括五种不同的绑定方法,以及如何为元素绑定多个相同事件。同时,文章讨论了元素创建的`delegate()`和`on()`方法,并对比了它们的区别。在事件解绑部分,讲解了`bind`、`delegate`和`on`的解绑方式。最后,阐述了事件冒泡的概念,并提供了阻止事件冒泡的方案。
摘要由CSDN通过智能技术生成

一、元素事件的绑定

为按钮绑定鼠标进入,鼠标离开,点击事件
第一种方法
            $("#btn").mouseenter(function () {
   
                $(this).css("backgroundColor","red");
            });
            $("#btn").mouseleave(function () {
   
                $(this).css("backgroundColor","blue");
            });
            $("#btn").click(function () {
   
                alert("你注定是一个与众不同的男人");
            });

第二种方式:链式编程
           $("#btn").mouseenter(function () {
   
                $(this).css("backgroundColor","red");
            }).mouseleave(function () {
   
                $(this).css("backgroundColor","blue");
            }).click(function () {
   
                alert("你注定是一个与众不同的男人");
            });
第三种方式:bind方法绑定事件
            $("#btn").bind("mouseenter",function () {
   
                $(this).css("backgroundColor","red");
            });
            $("#btn").bind("mouseleave",function () {
   
                $(this).css("backgroundColor","blue");
            });
            $("#btn").bind("click",function () {
   
                alert("你依旧这么的出众");
            });

第四种写法:链式编程
            $("#btn").bind("mouseenter",function () {
   
                $(this).css("backgroundColor","red");
            }).bind("mouseleave",function () {
   
                $(this).css("backgroundColor","blue");
            }).bind("click",function () {
   
                alert("你依旧这么的出众");
            });
第五种写法:使用键值对的方式绑定事件
               $("#btn").bind({
   "click":function () {
   
                    alert("你依旧这么的出众");
                },"mouseenter":function () {
   
                    $(this).css("backgroundColor","red");
                },"mouseleave":function () {
   
                    $(this).css("backgroundColor","blue");
                }});
为元素绑定多个相同的事件
  • bind方法绑定多个相同的事件的时候,如果使用的是键值对的方式,只能执行最后一个
第一种方式,可以
       $(function () {
   
            $("#btn").click(function () {
   
                console.log("就当他从来都没有来过");
            });
            $("#btn").click(function () {
   
                console.log("如果有一天");
            });
        });
第二种方式,可以
        $(function () {
   
            $(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值