问题
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?
You can test this FIDDLE
var counter = 0;
Using parent selector
$(".parent").on("click", "button.btn", function(){
$(".parent").append("<button class = 'btn'> new button " + (++counter) + "</button><br />");
});
or $(document)
$(document).on("click","button.btn",function(){
$(".parent").append("<button class = 'btn'> new button " + (++counter) + "</button><br />");
});
回答1:
You need to provide the closest parent selector which does not get dynamically generated and all the future element to whom event delegation is needed should be child elements of the static parent element.
when it comes to performance, delegating the event to closest static parent is more feasible compared to attaching to document or body of page.
回答2:
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.
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.
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.
来源:https://stackoverflow.com/questions/28823636/difference-of-document-and-parentselector-for-adding-events-of-dynamical