1
單擊某個按鈕時,其背景顏色不會像預期的那樣變爲黃色,也不會先前單擊的按鈕的背景顏色恢復爲紅色。我的目標是通過改變他們的類來改變按鈕的顏色。當按鈕的類被改變時,它們不會改變顏色。 testFunction()的用途是更新按鈕的顏色。 testFunction2()的作用是在按鈕上添加一個onclick函數。類更改時按鈕外觀未更新
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<style>
.button {
background-color: red;
}
.c {
background-color: yellow;
}
</style>
<body>
<table>
<tr>
<td>test1</td>
</tr>
<tr>
<td id="test1">
<button class="c">0</button>
<button class="">1</button>
<button class="">2</button>
<button class="">3</button>
</td>
</tr>
<tr>
<td>test2</td>
</tr>
<tr>
<td id="test2">
<button class="c">0</button>
<button>1</button>
<button>2</button>
<button>3</button>
</td>
</tr>
</table>
<script>
var lastClick1 = 0;
var lastClick2 = 0;
//alert('js');
function testFunction(c, n) {
// alert('tf');
if (c == 0) {
// alert('s=0');
if (lastClick1 != n) {
var a = document.getElementById("test1").children;
a[lastClick1].class = '';
a[n].class = 'c';
alert('n: ' + n + ' class: ' + a[n].class);
alert('lastclick:' + lastClick1 + ' class: ' + a[lastClick1].class);
lastClick1 = n;
}
} else {
// alert('else');
if (lastClick2 != n) {
var b = document.getElementById("test2").children;
b[lastClick2].class = '';
b[n].class = 'c';
alert('n: ' + n + ' class: ' + b[n].class);
alert('lastclick:' + lastClick2 + ' class: ' + b[lastClick2].class);
lastClick2 = n;
}
}
}
function testFunction2() {
//alert('tf2');
var t1 = document.getElementById("test1").children;
var t2 = document.getElementById("test2").children;
//alert(t1);
for (var i = 0; i < 6; i++) {
t1[i].onclick = function() {
testFunction(0, parseInt(this.innerText));
};
t2[i].onclick = function() {
testFunction(1, parseInt(this.innerText));
};
}
}
testFunction2();
</script>
</body>
</html>