[英]Match a table cell class and index using jQuery
以下代碼只是我想要應用於我的應用程序的理論的演示,因此使用THIS而不是td.flex不適合函數中的第二行。
我也必須出於其他原因使用.index而不是nth-child。
那都說:)
以下函數循環遍歷具有flex類的表的第一行中的所有TD。 對於每個記錄索引值。 下一行不是實際應用程序的一部分,但是為了測試該理論,應該找到具有一類flex的所有tds,其具有與cellIndex值匹配的索引值。 任何想法如何讓這個工作?
記住這段代碼是為了測試理論,因此為什么我不使用nth-child或者這個來應用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在最后的問候語中,表明數組現在保存元素的索引。 這應該給你一個工作知識,你想要完成你真正的工作:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.