使用jQuery匹配表格单元格类和索引

Match a table cell class and index using jQuery

本文关键字:索引 单元格 表格 jQuery 使用      更新时间:2023-09-26

下面的代码只是一个示范的理论,我想应用到我的应用程序,所以使用THIS而不是td。Flex不适合用于函数的第二行。

由于其他原因,我必须使用。index而不是n -child。

话虽如此

下面的函数循环遍历表第一行中具有flex类的所有TD。对于其中的每一个,记录索引值。下一行不是实际应用程序的一部分,但要测试理论,应该找到具有与cellIndex值匹配的索引值的flex类的所有tds。有什么办法让它工作吗?

请记住,这段代码是为了测试理论,因此为什么我不使用n -child或this来应用css着色!

cellIndex = new Array();
    $('table tr:first-child td.flex').each(function (i) {
        cellIndex[i] = $(this).index();
        $($('td.flex').index(cellIndex)).css('background-color', '#ff0000');
    });

如果我这样做:console.log($('td.flex').index(cellIndex));

我得到-1对于每个循环

只是为了确认我知道我可以这样做:

$(this).css('background-color', '#ff0000');

但是这个不是我试图用这个函数实现的,并且在实际应用程序中不起作用。

HTML例子:

<table>
<tr>
<td class="flex">Flex</td>
<td>Not Flex</td>
<td class="flex">Flex</td>
<td>Not Flex</td>
<td>Not Flex</td>
</tr>
</table>

每个函数已经包含一个索引系统。所以你可以这样使用它(cellIndex已经过时了):http://jsfiddle.net/TMFg3/

cellIndex = new Array();
$('table tr:first-child td.flex').each(function (i) {
    cellIndex[i] = i;
   $('td.flex:eq('+i+')').css('background-color', '#ff0000');
});

如果您不想使用cellIndex,那么您必须在每个函数之外循环它,因为您不能将数组发送到索引标识符,而且它将在每个循环中更改相同的目标:)

你当然也可以像这样使用cellIndex中的索引:

cellIndex = new Array();
$('table tr:first-child td.flex').each(function (i) {
    cellIndex[i] = i;
   $('td.flex:eq('+cellIndex[i]+')').css('background-color', '#ff0000');
});

如果您只是想遍历列表,您可以这样做:

$('table tr td:first-child td.flex').each(function (i) {        
    var cellIndex =$('table tr:first-child td').index(this);
    $('#hello').text($('#hello').text()+'"'+cellIndex+'",');
    $('td').eq(cellIndex).css('background-color', '#ff0000');    
}); 

假设以#hello标识的元素存在-那么它将包含"0","2",显示索引,并且元素将是红色背景。

将其放入数组:

$(document).ready(function(){
  var myCellIndexes=[];
  $('table tr td').parent().find('.flex').css('background-color','green');
  $('table tr:first-child td.flex').each(function (i) {        
    var cellIndex =$('table tr:first-child td').index(this);
    myCellIndexes[i]=cellIndex;
    $('#hello').text($('#hello').text()+'"'+cellIndex+'",');
    $('td').eq(cellIndex).css('background-color', '#ff0000');  
   }); 
   $('#hello').text($('#hello').text()+myCellIndexes);
});

的结果将是:"0","2",0,2在最后的hello中表明数组现在保存了元素的索引。这应该给你一个工作知识,你想要什么来完成你的实际工作:)