简体   繁体   中英

Jquery Selector using eq() with filter()

I would like to know if it is possible to use eq() with filter(). I've already tested it and to no avail, though I've found a work around. I was just wondering in case I missed something.

My example is this... Say you have a few tables with columns and rows.

<table class="menuTable"><tr><td>1</td><td>2</td></tr></table>
<table class="menuTable"><tr><td>3</td><td>4</td></tr></table>

I would like to find how many column spaces are in each table, so...

<script type="text/javascript">
alert($(".menuTable").eq(0).filter("td").length);
alert($(".menuTable").eq(1).filter("td").length);
</script>

This doesn't work and I'd like to find out why. I ended up using .find() instead of .filter(), but I think it would be more appropriate to use .filter().

Thanks for any input.

After a few comments I realize my problem is in the difference between find and filter. Also... for those who are curious. I did manage to get it to work using filter by including eq in the selector...

alert($(".menuTable:eq(0)").filter("td").length);

filter()过滤已经选择的元素,您正在寻找的是find() ,它可以在选择的元素中查找元素,实际上这将是用于此目的的正确方法!

alert($(".menuTable").eq(0).find("td").length);

Do you mean find out how many columns are in each table (not sure what "column spaces" means)? You can use find in this case:

$(document).ready(function() {
    alert($(".menuTable").eq(0).find("td").length);
    alert($(".menuTable").eq(1).find("td").length);
});

If you use a good JavaScript debugger (like in Chrome) or log to console, you can see that $('.menuTable').eq(0) is going to return the first table matched. Applying filter to that doesn't make sense -- it would make sense if you used find('td') and then wanted to filter the td elements based on say a class attribute.

Demo: jsfiddle

I ended up using .find() instead of .filter(), but I think it would be more appropriate to use .filter().

find is indeed what you should be using here. filter as the name suggests, filters the collection of elements, in your case that collection is all .menuTable elements; there are no td s in that collection. find on the other hand looks for children elements, and your collection does have td children elements.

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