简体   繁体   中英

Jquery select all children within children

I'm sure this will be a simple question but I still struggle with DOM selectors in Jquery so here is a model of my html code:

<fieldset class="product-options" id="product-options-wrapper">
   <ul class="options-list">
      <li><a href>Item1.1</a></li>
      <li><a href>Item1.2</a></li>
      <li><a href>Item1.3</a></li>
   </ul>

   ...other html items here

   <ul class="options-list">
      <li><a href>Item2.1</a></li>
      <li><a href>Item2.2</a></li>
      <li><a href>Item2.3</a></li>
   </ul>

</fieldset>

Now how do I select all of the 'li a' items in both lists (or X number of lists) with class name .options-list and bind them with a click function.

Currently I have:

$('fieldset#product-options-wrapper ul.options-list > li a').bind('click', function(e) {
     //code here
});

And it only gets the first options-list.

Thanks, greatly appreciated!

EDIT: If i click on a Item2.X list item first, then it will grab that options list. But as soon as I click on the Item1.x list items it disregards the second .options-list

How about $('.options-list a').bind('click', function(e) { }); ?

If you are going to bind to each li element, you should bind it to the ul element instead (helps greatly with performance when there are a lot of events).

$('.options-list', '#product-options-wrapper').bind('click', function(e)
{
   e.preventDefault();//In case you don't want to go to a different page
   var clicked = e.target;//The href that was clicked
   /* If you only want this to happen if the a tag was clicked, add the following line
   if(clicked.tagName == 'A')*/
   //Rest here
});

You can use delegate in this case to make it even simpler. Try this

$('#product-options-wrapper ul.options-list').delegate('li > a', 'click', function(e) {
     //code here
});

Your method seems sound to me. I created a test fiddle using your HTML (and an extra anchor to prove that it won't get the click added) and your JS (with minor modifications).

http://jsfiddle.net/chrisvenus/esZxH/1/

The selector you had did work but since you said you wanted the a to be a direct child of the li (or at least I read it that way) I slightly tweaked it in my version above. ARe you sure its not just your function is not doing quite what you want while executing or can you confirm that your click function isn't being run at all?

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