jQuery conditional selector for table rows

2019-04-20 21:50发布

问题:

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')")