我不确定我在这方面做错了什么。我已经动态地将类分配给行。这些类是有序的,一行可以具有相同的类。我想订购所有具有多个相同标识符的类,一种颜色。然后在返回原始颜色之前,下一组数字是另一种颜色。最后一行似乎总是失败。
<body>
<table>
<thead>Row</thead>
<tbody>
<tr class="a-1"><td>A1 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr> // should have class warning,but doesn't after js
<tr class="a-3"><td>A3 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr> // should have class warning,but doesn't after js
</tbody>
</table>
</body>
JQuery的
var flag = true;
$("table tr[class^='a-']").each(function(){
var current = $(this);
if((current.attr("class") == current.next().attr("class")) || (current.attr("class") == current.prev().attr("class"))){
if(flag){
current.addClass("info");
} else {
current.addClass("warning");
}
} else {
if(flag){
flag = false;
} else {
flag = true;
}
}
});
我制作了jsfiddle来展示我的问题
答案 0 :(得分:1)
$(function() {
var flag = true;
$("table tr[class^='a-']").each(function() {
var current = $(this);
var next = current.next();
var prev = current.prev();
var currentClassName = $(this).attr('class');
// alert(currentClassName);
if(next.hasClass(currentClassName) || prev.hasClass(currentClassName))
{
if(flag){
current.addClass("info");
} else {
current.addClass("warning");
}
}
else {
if(flag){
flag = false;
} else {
flag = true;
}
}
});
});
.info{background-color: blue;}
.warning{background-color: yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table>
<thead>Row</thead>
<tbody>
<tr class="a-1">
<td>A1 row</td>
</tr>
<tr class="a-2">
<td>A2 row</td>
</tr>
<tr class="a-2">
<td>A2 row</td>
</tr>
<tr class="a-2">
<td>A2 row</td>
</tr>// should have class warning,but doesn't after js
<tr class="a-3">
<td>A3 row</td>
</tr>
<tr class="a-4">
<td>A4 row</td>
</tr>
<tr class="a-4">
<td>A4 row</td>
</tr>
<tr class="a-4">
<td>A4 row</td>
</tr>
<tr class="a-4">
<td>A4 row</td>
</tr>// should have class warning,but doesn't after js
</tbody>
</table>
</body>
希望这有帮助
答案 1 :(得分:0)
这部分情况从未填满:
(current.attr("class") == current.prev().attr("class")
因为当你向它添加类“warning”或“info”时,所以即使它包含与当前元素相同的类,它也有其他类,并且它不相等。所以它更好,写出类似的东西:
var currClassName = "warning";
$("table tr[class^='a-']").each(function(){
var current = $(this);
var currClass = current.attr("class");
if((current.next().hasClass(currClass)) || current.prev().hasClass(currClass)){
current.addClass(currClassName);
}
else {
currClassName = (currClassName == "info") ? "warning" : "info";
}
});