简体   繁体   中英

jQuery weird issue with the selector

I have a question from my last post.

How to select second table structure under a div?

I have a new html set and it is like

<div class ='tableDiv'>
  <table class='table'>
    ....
  </table>

  <table class='table'>
    ....
  </table>

  <table class='table'>
    ....
  </table>


</div>

...other stuff...

<div class ='tableDiv'>
  <table class='table'>
    ....
  </table>

  <table class='table'>
    ....
  </table>

  <table class='table'>
    ....
  </table>

</div>

other stuff

<div class ='anotherTableDiv'>
  <table class='table'>
    ....
  </table>

  <table class='table'>
    ....
  </table>
</div>

I am trying to select every second table under ' tableDiv ' div.

from the last post I got.

$('.tableDiv table:even); as my last post answer

However, I now have 3 tables under ' tableDiv ' div and the selector seems to select second table from the first ' tableDiv ' and first table on the second ' tableDiv '

It is very weird as I thought even will select the second one from every div .

Can anyone help me about it? Thanks a lot!

jsFiddle Demo

尝试使用第nth-child选择器

$('.tableDiv table:nth-child(2)');//not 0 based

You'll need to change the selector so it gets the even tables from within each .tableDiv , right now it gets all the tables in the selector, and then selects the even tables from all tables etc.

You can do this easily by using find() or the context selector :

$('table:even', '.tableDiv')

This wont get you the second table, but the first and third, as that is what :even does (as noted in the comments, it's zero based, use :odd instead to get the second tables)

FIDDLE

You have the class name of the third table div set to 'anotherTableDiv' but the Jquery is targeting the '.tableDiv' class. either change the name of the class or make a separate Jquery to target the third table.

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