简体   繁体   中英

jQuery, click event doesn't fire

My problem was (because I solved it, but I don't know why it worked): I had two 'span' tags inside my DOM with the same CSS class. One span was added via AJAX request. I was trying to fire click event on them using:

$('.css class').on('click', function ...

but 'span' tag that was added second (AJAX) didn't produce click event. When I've changed above line to:

jQuery('body').on('click', '.css class', function(e){...

everything started to work as it should. I don't know why.

Use event delegation:

$('body').on('click','.css-class',function(){
 // your code goes here.
});

Remember not to have spaces in the class. Otherwise you'll be targeting <class> which is under the .css

on()

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers....

Read more

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