jQuery conditional selector for table rows

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I have a table with data in:

<td> item </td><td> order code </td><td> price </td>

I'm processing the table with jQuery which needs to find the order code:

$.each($('.productList tbody tr'), function() {     var orderCode = $(this).find('td:eq(1)').html().trim();     // do stuff }); 

If there are no products, the table shows a message:

<td colspan="3"> There are no products to display </td>

The above row causes the jQuery function to bomb out. What's the most robust way to use a conditional selector to ignore the "no products" row? Is there a selector for colspan="1" or colspan is not set or whatever it would need to be?

回答1:

Don't refine your selector, it won't scale well because jQuery will have to evaluate every child element. Avoid the error instead...

$('.productList tbody tr').each(function() {     var orderCode = $(this).find('td:eq(1)');     if(orderCode.length > 0) { // Make sure it exists      orderCode = orderCode.html().trim();       // do stuff     } });  


回答2:

Like this:

$('.productList tbody tr:has(td:nth-child(2))').each(function() {     ... }); 

This will only select <tr> elements that have a <td> that is the second child of its parent. (the nth-child selector is one-based)



回答3:

If you can change how you generate the table, using classes is a cleaner solution:

<td class="item-name"> item </td> <td class="order-code"> order code </td> <td class="item-price"> price </td> 

Then select only the desired class:

var orderCode = $(this).find('td.order-code').html().trim(); if(orderCode) {   //do stuff } 

This will also give you increased flexibility in styling the table with CSS, and your code won't break if you add or reorder columns.



回答4:

You could test how many tds there are:

$.each($('.productList tbody tr'), function() {     var tds = $(this).find('td');     if(tds.length >= 2) {         var orderCode = tds.eq(1).html().trim();         // do stuff     } }); 


回答5:

Use the .attr() method. Check out api.jquery.com and that should help you be able to figure out how to get the colspan attribute from your cells.



回答6:

More filtration to what SLaks has written

$("table tbody tr td:nth-child(2):contains('code')")



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!