I am a bit confused about using .on() Can someone tell me the difference between:
$('#detailData').on('click', '.select-topic', function() {
and
$('#detailData .select-topic').on('click', function() {
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first one delegates a click event handler to the
#detailDataelement. When a click event (that could come from any of its descendants) reaches that element, jQuery checks to see if the event target matches the selector,.select-topic. If it does, then the event handler is executed.This is useful if
.select-topicelements are added to the DOM dynamically – you can’t bind event handlers directly to elements that don’t exist yet.It’s possible because most DOM events bubble up the tree from the element on which they originate, up through all ancestor elements.
The 2nd example binds a click event handler to all
.select-topicelements that exist in the DOM at the time the code is executed.Here’s a simple demonstration. For the following markup:
Run the following code:
Attempt to click on “Item 3”, and nothing will happen. Comment out the first
.on()call, and uncomment the second. Run it again, and notice how the event handler now runs when you click on “Item 3”.