JQuery的on函数里面的selector作用

之前不知道on函数里面的selector是用来干嘛的,查了一下官方文档,里面是这样描述的

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

简单翻译一下就是说如果selector是被省略的或者值为null的话,那么事件处理函数被认为是直接绑定,当事件(比如click)发生在被绑定元素上或者是通过冒泡到达被绑定元素,都会触发事件处理函数。
而当你提供一个selector的时候,这时事件处理函数被认为是委托的。拿点击事件举例,当你直接点击该绑定元素时,事件处理函数不会被触发,只有当你点击该元素与selector匹配的后代元素时(无论是直接点击还是冒泡到该匹配元素),事件处理函数才会被触发。
听起来还是有点绕,举个例子理解一下。
这里我准备了三个盒子,它们的关系如下

 <body>
        <div>
            div
            <ul>
                ul
                <li>li</li>
            </ul>
        </div>
    </body>

在这里插入图片描述
1.当没有指定selector时:

 $('div').on('click',function(){
                console.log('我被点击了');
                console.log(this);
            })

我依次点击div,ul,li之后运行结果如下:
在这里插入图片描述
可以看到函数中的this都只是div,即被绑定元素。

2.当我指定selector之后再次依次点击div,ul,li:

$('div').on('click','ul',function(){
                console.log('我被点击了');
                console.log(this);
            })

在这里插入图片描述
可以看到第一次我点击div函数使没有被触发的,并且后来点击ul和li时函数都是被绑定在ul上,即selector元素。
最后再多说一点,使用selector的好处在于可以为动态创建的元素绑定事件处理函数,只要该元素是你绑定元素的后代。

$("#father").on("click", "#son", function() {
    // something
});

而通过jquery中的find函数找到后代再进行绑定是做不到的,它只能为你绑定已经存在于dom中的元素。

$("#father").find("#son").on("click", function() {
    // something
});
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值