tags:

views:

22

answers:

2

Hi,

I have the following:

<ul id='foo'>
  <li>
    <ul class='a'>
      <li class='animal'>goat</li>
      <li class='animal'>horse</li>
      <li class='animal'>pig</li>
    </ul>
  </li>
  <li>
    <ul class='a'>
      <li class='animal'>zebra</li>
    </ul>
  </li>
</ul>

I want to make a delegate handler for the inner li items (the ones with class 'animal'):

$('#foo li ul').delegate('li', 'click', function(event) {
    ...
});

I'm not sure how to define the selector though in the delegate definition - what's the right way to do it?

Thanks

+1  A: 

You can do it like this:

$('#foo').delegate('li.animal', 'click', function(event) {
  //do something
});

The initial selector is where the listener for the clicks should live (they'll bubble up to here), the first parameter (li.animal) is what elements to listen for a click from.

Nick Craver
A: 

The following should work...

$('#foo').delegate('ul.a li', 'click', function(event) {
    ...
});

This will also work, but will attach the handler to every ul.a element which is losing the benefits of .delegate IMO :)

$('#foo ul.a').delegate('li', 'click', function(event) {
    ...
});
Shrikant Sharat