开发者

jQuery AND selector

I have a datagrid(asp.net) on my page. I would like to select all rows that has the word 'foo' in the first column AND the word 'bar' in the second column.

I only know how to do it for the first column.

jQuery('[id$="datagrid1"] tr td:contains(foo)')

Can anyone ple开发者_运维百科ase let me know how to include the condition for the second column which has the word 'bar'?

Edit: Also, how do I match the word exactly? As selector contains matches when the cell contains the word.


Selectors only get you so far. Use .filter() for greatest flexibility:

jQuery('[id$="datagrid1"] tr').filter(function () {
    return $('td:eq(0)', this).text() == 'foo' &&
        $('td:eq(1)', this).text() == 'bar';
});
  • The .filter() functions iterates through each element and expects you to return true or false to indicate whether the element should be kept (matches).
  • The :eq() selector lets you choose an index within the matched set.


Like this:

jQuery('[id$="datagrid1"] tr').filter(function(){
   var $tds = $(this).find("td");
   return ($tds.eq(0).text()=="foo" && $tds.eq(1).text()=="bar");
});

The same code more 'explained'

$trs = jQuery('[id$="datagrid1"] tr').filter(function(){
   var $first_td = $(this).find("td").eq(0);  //First column
   var $second_td = $(this).find("td").eq(1); //Second column
   return ($first_td.text()=="foo" && $second_td.text()=="bar"); //Condition to filter
});

This returns a set of <tr> that match the condition you want.

Hope this helps. Cheers


You can use the next-sibling selector assuming the second column <td> is adjacent to the first column <td>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜