javascript - What is the better way to add an event to a descendant element in jQuery? -
i tried 2 approaches both worked fine. there reason should use 1 on other?
first approach:
$('div.parent').find('.cancel-btn').on('click', function(){ alert('cancel clicked'); });
second approach:
$('div.parent').on('click', '.cancel-btn', function(){ alert('cancel clicked'); });
from reading of docs seem similar except second 1 fire event if child element not exist. interesting.
and deduce first version wires click event listener on target (.cancel-btn) element. spends time finding element when listener created, , there no dom traversal requirement when click event fires listener.
meanwhile second option wires listener click event parent searches out child when event fires.
therefore in theory there finite performance difference user perspective of second option. though impact of depend on element density , tree makeup of page.
i guess in cases time impact small unimportant. in case true difference point second option firing irrespective of presence of child element.
Comments
Post a Comment