jQuery核心对象——事件

本文详细介绍了jQuery中的事件绑定、解绑、坐标获取、mouseover/mouseenter区别,以及事件委派的原理、应用和优势。通过实例演示了如何使用事件委托来处理大量动态生成的元素,提升代码效率。
摘要由CSDN通过智能技术生成

页面载入

  • ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){
  // 在这里写你的代码...
});

简写:
使用 $(document).ready() 的简写,同时内部的 jQuery 代码依然使用 $ 作为别名,而不管全局的 $ 为何。

$(function($) {
  // 你可以在这里继续使用$作为别名...
});

事件处理

  • on(events,[selector],[data],fn):在选择元素上绑定一个或多个事件的事件处理函数。
  • off(events,[selector],[fn]):在选择元素上移除一个或多个事件的事件处理函数。
  • bind(type,[data],fn):为每个匹配元素的特定事件绑定事件处理函数。
  • one(type,[data],fn):为每一个匹配元素的特定事件(像click)绑定一个一次性的事件处理函数。
  • trigger(type,[data]):在每一个匹配的元素上触发某类事件。
  • triggerHandler(type, [data]):这个特别的方法将会触发指定的事件类型上所有绑定的处理函数。但不会执行浏览器默认动作,也不会产生事件冒泡。
  • unbind(type,[data|fn]]):bind()的反向操作,从每一个匹配的元素中删除绑定的事件。

eg:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <style>
      .out{
        width: 300px;
        height: 300px;
        background-color: coral;
      }
      .inner{
        margin-top: 100px;
        width: 100px;
        height: 100px;
        background-color: darkcyan;
      }
    </style>
  </head>
  <body>
    <div class="out">
      外部div
      <div class="inner">内部div</div>
    </div>

    <div class="divBtn">
      <button id = 'btn1'>取消绑定所有事件</button>
      <button id = 'btn2'>取消绑定mouseover事件</button>
      <button id = 'btn3'>测试事件坐标</button>
      <a href="http://www.baidu.com" id="text4">百度一下</a>
    </div>

    <script type='text/javascript' src='./jquery库/jquery-1.12.4.js'></script>
    
    <script>
    /* 1.给.out绑定点击监听(用两种方法绑定)
     $('.out').click(function (){
        console.log('click out')
     })*/
    $('.out').on('click',function (){
       console.log('click out')
    })
// on更通用,极个别没有click()地方法

    // 2.给.inner绑定鼠标移入和移出的事件监听(用3种方法绑定)
   /* $('.inner')
    .mouseenter(function (){
      console.log('进入')
    })
    .mouseleave(function (){
      console.log('离开')
    })*/
    /*$('.inner')
    .on('mouseenter',function (){
       console.log('进入')
    })
    .on('mouseleave',function (){
      console.log('离开')  
    })*/
    $('.inner').hover(function (){
       console.log('进入')
    },function (){
       console.log('离开')
    })
    // hover 底层调用的还是mouseenter

    // 3.点击btn1解除.inner上的所有事件监听
    $('#btn1').click(function (){
       $('.inner').off()
    })
    // 4.点击btn2解除.inner上的mouseover事件
    $('#btn2').click(function (){
       $('.inner').off('mouseenter')
    })
    // 5.点击btn3得到事件坐标
    $('#btn3').click(function (event){//event
       console.log(event.offsetX,event.offsetY)//原点:事件元素
       console.log(event.clientX,event.clientY)//窗口左上角
       console.log(event.pageX,event.pageY)//页面左上角
    })
    // 6.点击.inner区域,外部点击监听不响应
    $('.inner').click(function (event){
       console.log('inner')
       event.stopPropagation()
       
    })
    // 7.点击链接,如果当前时间是偶数不跳转
    $('#test4').click(function (event){
       if(Date.now()%2 === 0){
          event.preventDefault()
       }
    })
    </script>
    
  </body>
</html>

总结

1. 事件绑定(2种):

  • eventName(function(){})
    绑定对应事件名的监听,例如:
$('#div').click(function(){});
  • on(eventName, funcion(){});
    通用的绑定事件监听,例如:
$('#div').on('click', function(){})
  • 优缺点:
    eventName:编码方便,但只能加一个监听,且有的事件监听不支持
    on:编码不方便,可以添加多个监听,且更通用

2.事件解绑:

  • off(eventName)

3.事件的坐标

  • event.cliehtX, event.clientY相对于视口的左上角
  • event.pageX, event.pageY相对于页面的左上角
  • event.offsetX,event.offsetY相对于事件元素左上角

4.事件相关处理

  • 停止事件冒泡: event.stopPropagation()
  • 阻止事件默认行为: event.preventDefault()

区分mouseover 与mouseenter

  • mouseover:在移入子元素时也会触发,对应mouseout
  • mouseenter:只在移入当前元素时才触发,对应mouseleave
  • hover()使用的就是mouseenter( )未mouseLeave()

所以如果没有子元素两者效果是一样的。

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>mouserover</title>
    <style>
        
        .div1{
            width: 300px;
            height: 300px;
            background-color: darkgoldenrod;
            text-align: center;
            display: inline-flex; 
            justify-content: center;
            align-items: center;
        }
        .div2{
            width: 100px;
            height: 100px;
            background-color: darkorange;
        }
        .div3{
            width: 300px;
            height: 300px;
            background-color:darksalmon;
            text-align: center;
            display: inline-flex; 
            justify-content: center;
            align-items: center;
        }
        .div4{
            width: 100px;
            height: 100px;
            background-color:darkseagreen;
        }
    </style>
</head>
<body>
    <div class="divText">
        区分鼠标事件
    </div>
    <div class="div1">
        div1
        <div class="div2">div2</div>
    </div>
    <div class="div3">
        div3
        <div class="div4">div4</div>
    </div>

    <script type='text/javascript' src='./jquery库/jquery-1.12.4.js'></script>
    <script>
        $('.div1')
        .mouseover(function (){
           console.log('mouseover进入')       
        })
        .mouseout(function (){
            console.log('mouseout退出')       
        })

        $('.div3')
        .mouseenter(function (){
           console.log('mouseenter进入')       
        })
        .mouseleave(function (){
            console.log('mouseleave退出')       
        })

    </script>
    
</body>
</html>

区分:on( 'click ’ , fun)与click(fun)

  • on( 'eventName ', fun):通用,但编码麻烦
  • eventName(fun):编码简单,但有的事件没有对应的方法

事件委派

问题的产生

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件委派</title>
</head>
<body>
    <ul>
        <li>11111</li>
        <li>11111111</li>
        <li>11111111111</li>
        <li>11111111111111</li>
    </ul>
    <li>22222</li>
    <br>
    <button id='btn'>添加新的li</button>
    <script type='text/javascript' src='./jquery库/jquery-1.12.4.js'></script>
    <script>
        // 1.点击Li背景就会变为红色
        $('ul>li').click(function (){
           this.style.background = 'red'
        })
         // 2.点击btn1就添加一个Li
         $('#btn').click(function (){
            $('ul').append('<li>新增的li</li>')
         })

        //  问题新增的li不会添加监听事件

    </script>
</body>
</html>

问题:新增的li不会添加监听事件
解决:事件的委派

事件委派

事件委托(委派/代理):
即:

  • 将多个子元素(li)的事件监听委托给父辈元素(ul)处理
  • 监听回调是加在了父辈元素上
  • 当操作任何一个子元素(li)时,事件会冒泡到父辈元素(uL)
  • 父辈元素不会直接处理事件,而是根据event.target得到发生事件的子元素(li),通过子元素调用回调函数。
    (所以回调函数的父元素是发生时间的子元素)

事件委派使用

设置事件委派:$(parentSelector).delegate(childrenSelector,eventName,callback )

$("父元素").delegate("子元素","监听事件",function(){
  回调函数
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件委派</title>
</head>
<body>
    <ul>
        <li>11111</li>
        <li>11111111</li>
        <li>11111111111</li>
        <li>11111111111111</li>
    </ul>
    <li>22222</li>
    <br>
    <button id='btn'>添加新的li</button>
    <script type='text/javascript' src='./jquery库/jquery-1.12.4.js'></script>
    <script>
       $('ul').delegate('li','click',function (){
        //   this是li
        this.style.background = 'red'
       })
        $('#btn').click(function (){
            $('ul').append('<li>新增的li</li>')
       })
    </script>
</body>
</html>

移除事件委派

删除事件委派:$(parentSelector ).undelegate(eventName)

$("父元素").undelegate('监听事件');

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件委派</title>
</head>
<body>
    <ul>
        <li>11111</li>
        <li>11111111</li>
        <li>11111111111</li>
        <li>11111111111111</li>
    </ul>
    <li>22222</li>
    <br>
    <button id='btn'>添加新的li</button>
    <button id='btn2'>移除ul上的事件委派</button>
    <script type='text/javascript' src='./jquery库/jquery-1.12.4.js'></script>
    <script>
        // 设置事件委托
       $('ul').delegate('li','click',function (){
        //   this是li
        this.style.background = 'red'
       })
        $('#btn').click(function (){
            $('ul').append('<li>新增的li</li>')
       })
     $('#btn2').click(function (){
        // 移除事件委托
        $('ul').undelegate('click')
     })

    </script>
</body>
</html>

事件委派的方法

  • live(type, [data], fn): jQuery 给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的也有效。
  • die(type, [fn]):从元素中删除先前用.live()绑定的所有事件.(此方法与live正好完全相反。)
  • delegate(selector,[type],[data],fn):指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。
  • undelegate([sel,[type],fn]):删除由 delegate() 方法添加的一个或多个事件处理程序。

使用事件委托的好处

  • 添加新的子元素,自动有事件响应处理
  • 减少事件监听的数量: n==>1

事件切换

  • hover([over,]out):一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。
  • toggle([speed],[easing],[fn]): 用于绑定两个或多个事件处理器函数,以响应被选元素的轮流的 click 事件。

事件

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值