gpt4 book ai didi

javascript - JQuery 比较类名

转载 作者:行者123 更新时间:2023-12-03 05:45:03 25 4
gpt4 key购买 nike

我不确定我在这方面做错了什么。我已将类动态分配给行。这些类是有序的,一行可以有相同的类。我想订购具有多个相同标识符一种颜色的所有类。然后下一组数字使用替代颜色,然后再返回原始颜色。但最后一行似乎总是失败。

<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显示我的问题

最佳答案

$(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>

希望这有帮助

关于javascript - JQuery 比较类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40362076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com