$(document)和$('parentSelector')用于动态添加元素的添加事件的区别? [英] Difference of $(document) and $('parentSelector') for adding events of dynamically add element?

查看:65
本文介绍了$(document)和$('parentSelector')用于动态添加元素的添加事件的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用$(document)作为click event的选择器感到困惑吗?是否有任何差异或cos而不是仅使用父选择器? 两者都产生相同的输出,但是是否有执行速度之类的因素?

I am confused with the $(document) in using this as my selector for a click event? Any difference or cos instead of using only the parent selector? Both of them produces the same output but is there any factor like executing speed?

您可以测试 FIDDLE

var counter = 0;

使用父级选择器

    $(".parent").on("click", "button.btn", function(){
        $(".parent").append("<button class = 'btn'> new button  " + (++counter) + "</button><br />");
    });

或$(document)

    $(document).on("click","button.btn",function(){
        $(".parent").append("<button class = 'btn'> new button  " + (++counter) + "</button><br />");
    });

推荐答案

通常应绑定到包含要委派给动态元素的限制性最强的元素.委派的工作方式是,每次事件在您绑定到的元素中的任何位置发生时,都会运行内部jQuery处理程序.该处理程序执行检查以查看目标是否与选择器参数匹配,如果匹配,则调用您的处理程序函数.

You should generally bind to the most restrictive element that contains the dynamic elements that you want to delegate to. The way delegation works is that an internal jQuery handler is run every time the event occurs anywhere in the element that you bind to. This handler performs a check to see if the target matches the selector argument, and if so it calls your handler function.

因此,如果您使用$(document).on,则只要在页面上单击任意位置,就必须进行此检查.但是,如果使用$(".parent").on,则仅在单击父元素内部时才需要进行检查.这会减少浏览器的开销.

So if you use $(document).on, it will have to do this check anytime you click anywhere on the page. But if you use $(".parent").on it only has to do the check when you click inside the parent element. This is less overhead on the browser.

此外,委派取决于事件冒泡到绑定到的元素.如果存在一个包含button.btn的元素,并且它具有一个调用event.stopPropagation()的点击处理程序,则它将取消冒泡,并且jQuery的内部处理程序将永远不会运行.绑定到父级应该使这不太可能.

Also, delegation depends on the event bubbling out to the element you bind to. If there's an element that contains button.btn and it has a click handler that calls event.stopPropagation(), this will cancel the bubbling, and the jQuery's internal handler will never be run. Binding to the parent should make this unlikely.

这篇关于$(document)和$('parentSelector')用于动态添加元素的添加事件的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆