Using CSS, it's very easy to attach a certain style for all elements sharing the same class. I would like to do something similar, but for DOM event handlers rather than styles. Eg I'd like all elements with class my-class
will have the same handler for a click event.
I know this can be done easily using a selector after the page is loaded, eg in jQuery:
$('.my-class').click(function() {alert('clicked');})
but I wonder if this can be achieved using DOM event delegation. The canonical answer suggests that delegation can be used to propagate an event from a child node to its parent (or ancestor, in general). Is it possible to define a handler on a single node with my-class
, and have all the other elements with my-class
delegate to it, even if they aren't descendents?
Although considered bad practice (because you should generally delegate to the nearest static ancestor), you can delegate to the body
element as follows:
$('body').on('click', '.my-class', function() {
alert('clicked');
});
This will of course delegate click events on any elements with a class of my-class
that are in the body
of your document.
We can also trigger the event when a different element is clicked:
$( "#other" ).click(function() {
$( "#target" ).click();
});
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.