2016-12-13 5 views
0

値に応じて行の色を入れたいテーブルの行を同じ色で表示する

ここはコードですが、常に最初の色が使用されます。

$(document).ready(function() { 
    $('#myTable td.xs').each(function() { 
    if ($(this).text() < 10) { 
     $(this).closest('tr').css('background-color', 'green'); 
    } else { 
     $(this).closest('tr').css('background-color', 'red'); 
    } 
    }); 
}); 

HTML:最後<td>を持っているので<tr>あなたの場合

<tr class="xs"> 
    <td class="xs">5/td> 
    <td class="xs">10</td> 
    <td class="xs">12</td> 
</tr> 

答えて

1

、すべて<td>のシェアと同じなので、ループによって設定された最後の色は、(あなたの例では赤を獲得します25)。したがって、<td>の色を変更する必要がありますか、または<td>を個体<tr>に入れる必要がありますか、または<tr>のうちどれを使用するかについてより具体的にする必要があります。

オプション1:<td>の色を変更:

$(document).ready(function() { 
 
    $('#myTable td.xs').each(function() { 
 
    if ($(this).text() < 10) { 
 
     $(this).css('background-color', 'green'); 
 
    } else { 
 
     $(this).css('background-color', 'red'); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable"> 
 
    <tr class="xs"> 
 
    <td class="xs">5</td> 
 
    <td class="xs">10</td> 
 
    <td class="xs">12</td> 
 
    </tr> 
 
</table>

オプション2:個別<tr>

$(document).ready(function() { 
 
    $('#myTable td.xs').each(function() { 
 
    if ($(this).text() < 10) { 
 
     $(this).closest('tr').css('background-color', 'green'); 
 
    } else { 
 
     $(this).closest('tr').css('background-color', 'red'); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable"> 
 
    <tr class="xs"> 
 
    <td class="xs">5</td> 
 
    </tr> 
 
    <tr class="xs"> 
 
    <td class="xs">10</td> 
 
    </tr> 
 
    <tr class="xs"> 
 
    <td class="xs">12</td> 
 
    </tr> 
 
</table>

+0

もし私がtrタグをテーブルタグで囲まなければ。私は '$( 'tr')'にアクセスできません。 – Mahi

+0

@PraveenKumar色を変更することはどういう意味ですか? –

+1

@Mahiそれはまったく失敗するでしょう。あなたはその構造に従う必要があります。 「」または「​​」または「」タグは、「

」のうち存在しません。 –

関連する問題