简体   繁体   中英

jQuery how to select td with rowspan attribute?

The code below can get the html table tds with attribute 'rowspan',

 $elem.find('td').filter('[rowspan]') 

but how can I get the tds who's 'rowspan' is more than 1,like:

$elem.find('td').filter('[rowspan > 1]')

You can apply a function to your filter and return elements whose rowSpan is greater than 1 :

$.elem.find('td').filter(function() {
  return this.rowSpan > 1;
});

Note that there's no need to wrap attr() or re-wrap this (as $(this) ) as rowSpan is a native element property (which is conveniently already a numeric type, so no number conversion is needed).

Example

 $('td').filter(function() { return this.rowSpan > 1; }).css('color', 'red') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <td>No rowspan</td> <td rowspan=1>Rowspan 1</td> <td rowspan=2>Rowspan 2</td> </tr> </tbody> </table> 

Try something like this :-

$elem.find('td').filter(function(){
   return (parseInt($(this).attr('rowspan'),10) > 1);
});

使用: parseInt($(this).attr('rowspan'),10) > 1

You can iterate in each td element and check if attribute rowspan is > 1. In my example I use css class to represent if a td has rowspan > 1 adding to this element class pass or fail accordingly.

 $("table tbody tr td[rowspan]").each(function() { $(this).addClass(parseInt($(this).attr("rowspan"), 10) > 1 ? "pass" : "fail"); }); 
 .pass { background: green; } .fail { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <td rowspan='2'>2</td> <td rowspan='3'>3</td> <td>no rowspan</td> <td rowspan='1'>1</td> </tr> <tr> <td rowspan='2'>2</td> <td rowspan='3'>3</td> <td>no rowspan</td> <td rowspan='1'>1</td> </tr> <tr> <td rowspan='2'>2</td> <td rowspan='3'>3</td> <td>no rowspan</td> <td rowspan='1'>1</td> </tr> </tbody> </table> 

To get the tds who's 'rowspan' is more than 1, you may try the following:

var allTdsWithMoreThanOneRowspan = $elem.find('td[rowspan]').filter(function () {   
   return ($(this).attr('rowspan') > 1);
})

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