简体   繁体   中英

jQuery css selector for table

I'm having the following table markup:

<table>
    <tr><td>foo</td><td class=marked>foo</td><td>foo</td></tr>
    <tr><td class=marked>foo</td><td class=marked>foo</td><td class=marked>foo</td></tr>
    <tr><td>foo</td><td>foo</td><td>foo</td></tr>
    <tr><td>foo</td><td>foo</td><td class=marked>foo</td></tr>
</table>

Several cells are marked with class marked - how can I select all rows which have cells with class marked ? I know how to select all marked cells but I need the rows for the selector in order to loop through them.

What I want to achieve is an array/JSON string which contains all data of all rows with cell indexes of the marked cells, which would look something like that:

rowdata[0] = [1];
rowdata[1] = [0,1,2];
rowdata[3] = [2];

Any ideas what's the easiest way to to it?

EDIT: Sorry, there was a typo, I meant class "marked"

Try like

var rowdata=[];

$('tr').each(function(){
   $td=$(this).find('td');
   arr=[];
   $td.each(function(index,value){
       if($(this).hasClass('marked'))
          arr.push(index);
   });
   rowdata.push(arr);
});

Fiddle

var rowdata = [];
$('table tr').each(function () {
    rowdata.push($(this).find('.marked').map(function () {
        return $(this).index();
    }).get());
});

DEMO

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