简体   繁体   English

(jQuery)选择document.body而不是Parent元素

[英](jQuery) Selecting document.body instead of Parent Element

This part of code is an answer from this question . 这部分代码是该问题的答案。

$(document.body).on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

I Have two questions the first one is. 我有两个问题,第一个是。 Is there a performance issue selecting 'document.body' instead of selecting the Parent element of select? 在选择“ document.body”而不是选择select的Parent元素时是否存在性能问题? Something like this. 这样的事情。

Second question is. 第二个问题是。 It will be function like '$.live()' when putting Parent element instead of document.body? 当放置Parent元素而不是document.body时,它的功能类似于'$ .live()'

$("#IdOfParentHere").on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

Thanks! 谢谢!

Is there a performance issue selecting 'document.body' instead of selecting the Parent element of select? 在选择“ document.body”而不是选择select的Parent元素时是否存在性能问题?

No. There is no significant difference in performance. 否。性能没有明显差异。 Of course it would be a little faster if you put it closer on the DOM, but we are talking about an incalculably small difference. 当然,如果您将其放在DOM上会更快一些,但是我们正在谈论的是一个不可估量的微小差异。

Second question is. 第二个问题是。 It will be function like '$.live()' when putting Parent element instead of document.body? 当放置Parent元素而不是document.body时,它的功能类似于'$ .live()'?

$.live does exactly the same thing as $("body").on("click", "selector", $.live$("body").on("click", "selector",

There could be a performance impact(not much significant though) when attaching event handlers to body instead parent element. 将事件处理程序附加到主体而不是父元素时,可能会对性能产生影响(尽管影响不大)。

Take a case where you are trying to delegate a click event, what you really want to is to handle dynamically created li elements which are in a static ul element. 例如,在尝试委派click事件的情况下,您真正​​想要的是处理静态ul元素中动态创建的li元素。 In event delegation when an event happens inside the attached element that events target will be evaluated against the delegation selector to see whether to trigger the handler. 在事件委托中,当事件发生在附加元素中时,将针对委托选择器评估事件目标,以查看是否触发处理程序。 In this case if the event is attached to the ul only events inside the ul has to be tested, but if the hanlder is attached to body all the click in the page will have to be tested. 在这种情况下,如果将事件附加到ul仅需测试ul内部的事件,但是如果将hanlder附加到主体,则必须测试页面中的所有单击。

The l ive() method attaches the handler to the document object, so yes it will be similar to that. live()方法将处理程序附加到文档对象,因此可以。

This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. 此方法提供了一种将委派事件处理程序附加到页面的document元素的方法,从而可以在将内容动态添加到页面时简化事件处理程序的使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM