我有以下代码:
var classCode = "";
var colorUsed = [];
var classes = [];
var color = ["yellow", "lightblue", "lightgreen", "pink", "orange", "cyan", "lightgrey", "plum", "wheat", "khaki"];
function colorClass(row) {
classCode = $(row).html();
var index = -1;
if (colorUsed.length != 0) {
index = classes.indexOf(classCode);
} else {
index = -1;
}
while (index == -1) {
colorNum = Math.floor((Math.random() * 10));
if (!(color[colorNum] in colorUsed)) {
colorUsed.push(color[colorNum]);
classes.push(classCode);
index = 1;
} else {
alert("same color!");
index = -1;
}
}
if (index != -1) {
colorNum = classes.indexOf(classCode);;
}
$(row).css("background-color", colorUsed[colorNum]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
</thead>
<tbody>
<tr><td colspan="3" onclick="colorClass(this);">ClassA</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassC</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassD</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassE</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassF</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassG</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassH</td></tr>
</tbody>
</table>
我使用“in”函数来避免应用相同的颜色,但它不起作用,我知道还有另一种方法可以使用它来逐个循环元素并进行比较,但我不喜欢使用它。
或者有其他方法可以检测它吗?由于javascript中没有hashset,是否可以在Jquery中实现?
最佳答案
尝试写作
if (!(color[colorNum] in colorUsed)) {
作为
if (colorUsed.indexOf(color[colorNum]) == -1) {
希望有帮助:)
关于javascript 无法检测数组中的相同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40377203/