简体   繁体   中英

(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? Something like this.

Second question is. It will be function like '$.live()' when putting Parent element instead of document.body?

$("#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?

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.

Second question is. It will be function like '$.live()' when putting Parent element instead of document.body?

$.live does exactly the same thing as $("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. 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.

The l ive() method attaches the handler to the document object, so yes it will be similar to that.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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