我有一个很大的id列表,在这个例子中:" 1,2,4"
如何遍历表中的所有行并将类添加到与数组中的类匹配的行内? (使用jQuery / javascript)
所以这个表:
<table>
<tr class="row-1">
<td><span class="foo">1</span></td>
</tr>
<tr class="row-2">
<td><span class="foo">2</span></td>
</tr>
<tr class="row-3">
<td><span class="foo">3</span></td>
</tr>
<tr class="row-4">
<td><span class="foo">4</span></td>
</tr>
<tr class="row-5">
<td><span class="foo">5</span></td>
</tr>
</table>
之后看起来像这样:
<table>
<tr class="row-1">
<td><span class="foo bar">1</span></td>
</tr>
<tr class="row-2">
<td><span class="foo bar">2</span></td>
</tr>
<tr class="row-3">
<td><span class="foo">3</span></td>
</tr>
<tr class="row-4">
<td><span class="foo bar">4</span></td>
</tr>
<tr class="row-5">
<td><span class="foo">5</span></td>
</tr>
</table>
答案 0 :(得分:4)
var array = [1,2,4]; // etc...
$(array.map(function(i) {return ".row-" + i;}).join(',')).addClass('bar');
在es6中:
const array = [1,2,4]; // etc...
$(array.map(i => `.row-${i}`).join(',')).addClass('bar');
修改您也可以直接使用reduce,即(es6)
$(`.row-${array.reduce((a, b) => `${a},.row-${b}`)}`).addClass('bar');
答案 1 :(得分:1)
试试这个
var ids = [1,2,4];
$( "tr[class^='row']" ).each( function(){
var index = parseInt( $(this)[0].className.split("-")[1], 10 );
if( ids.indexOf( index ) != -1 )
{
$(this).addClass("bar");
}
});
.bar
{
color :red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="row-1">
<td><span class="foo">1</span></td>
</tr>
<tr class="row-2">
<td><span class="foo">2</span></td>
</tr>
<tr class="row-3">
<td><span class="foo">3</span></td>
</tr>
<tr class="row-4">
<td><span class="foo">4</span></td>
</tr>
<tr class="row-5">
<td><span class="foo">5</span></td>
</tr>
</table>
答案 2 :(得分:0)
你可以试试这个:
$("tr[class*='row'] td span").addClass('foo')