Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on/delegate correct syntax

As the jQuery API is currently down, is anyone able to assist me with the below? I am ajax loading an unordered list into the web page and need to be able to attach hover and click events to the list items.

<ul>
  <li class="option">Item 1</li>
  <li class="option">Item 1</li>
  <li class="option">Item 1</li>
</ul>

So far I have tried a few variations of the below jQuery code using .on for version 1.7+

$("ul").on("click", "li .option", function(){
alert($(this).text());
}); 

Can anyone point me in the right direction? I'm aware that .live has been deprecated and that .delegate has been superseded so really only looking for a solution that will allow me to use .on.

like image 935
KryptoniteDove Avatar asked Jan 20 '26 12:01

KryptoniteDove


1 Answers

Not li .option, because it find element within li with class option, but you have this class to li, so it will be li.option or .option.

So for .on(), it looks like:

$("ul").on("click", "li.option", function(){
   alert($(this).text());
});

But for .delegate(), it looks like:

$("ul").delegate("li.option", "click", function(){
   alert($(this).text());
});

According to you edit

you're trying to bind click to li.option with container reference ul, which is also append to DOM alter. So you can go for #content, which already exists in DOM ans where you append you whole list.

So delegate event will looks like:

$("#content").delegate("ul > li.option", "click", function(){
   alert($(this).text());
});
like image 176
thecodeparadox Avatar answered Jan 22 '26 05:01

thecodeparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!