I’ve been thinking a bit about how to add a function to ‘.click()’ event on a <ul>‘s very own <li>s. First thing would be simple with (it’s approximative, I’m not a jquery pro obviously).
$(document).ready(
function () {
$('.prodli').each().click( //prodli is my class I set on every <li>
function () {
//blabla
}
);
}
);
BUT! Because there’s always a but somewhere… Thing is these <li> can be removed added through another jquery script.
So if I apply previous script I wrote above on this list:
<ul>
<li productId="1" class="prodli">Product 1</li>
<li productId="2" class="prodli">Product 2</li>
<li productId="3" class="prodli">Product 3</li>
<li productId="4" class="prodli">Product 4</li>
<li productId="5" class="prodli">Product 5</li>
<li productId="6" class="prodli">Product 6</li>
</ul>
I suppose that if with some other scripts I update the list to be something like
<ul>
<li productId="455" class="prodli">Product 455</li>
<li productId="48" class="prodli">Product 48</li>
<li productId="7" class="prodli">Product 7</li>
</ul>
I should re-call my first script to apply the click() function to these new <li>, right?
Is there a way to do it in a more global way? I mean something like “every time an element with class “prodli” is clicked, apply this function” ? Or something like every <li> from this specific <ul> list ?
Thanks a lot guys!
You can delegate the click event to the parent
ulelement (or any other ancestor really). Since DOM events tend to bubble up the tree, any click on a descendant element will reach theuland can be handled there.jQuery provides the
onmethod to do so (if you’re using an older version of jQuery you will needdelegateinstead ofon):This means the children of the
ulcan change as much as you like. It won’t make a difference. Any click on any descendant of theulwill bubble up to theul. jQuery checks to see if the click originated on an element matching the selector (in this case, any.prodlielement), and if so it executes the event handler.