我需要做以下事情: 创建一个4x4表(16个方格),每个接收鼠标点击的表格单元格(正方形)应将其颜色背景更改为绿色并在变量中接收值“1”(不打算显示数字“1”)在标记的单元格中,但只在变量中记录此值,以便将有多少单元格的颜色总和)。
全部谢谢!
答案 0 :(得分:0)
var count;
$('td').on('click',function() {
$(this).css('background-color','#cccccc');
count++;
});
count应该具有单击的单元格数量,并且背景颜色也将更改。我假设使用jQuery是可以的。
答案 1 :(得分:0)
试试这个: -
HTML:
<table id="clickable-table">
<tr class="row">
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
</tr>
<tr class="row">
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
</tr>
<tr class="row">
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
</tr>
<tr class="row">
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
<td class="column"></td>
</tr>
JS / jQuery的: -
var count = 0;
$(".column").off("click").on("click",function(){
$(this).css("background-color","green");
count++;
console.log(count);
});
CSS:
td.column {
width: 25px;
height: 25px;
border: solid 1px;
}
答案 2 :(得分:0)
HTML
<table width="50%">
<tbody><tr>
<td id="cell1" class="tblCell none">1</td>
<td id="cell2" class="tblCell none">2</td>
<td id="cell3" class="tblCell none">3</td>
<td id="cell4" class="tblCell none">4</td>
</tr>
<tr>
<td id="cell5" class="tblCell none">5</td>
<td id="cell6" class="tblCell none">6</td>
<td id="cell7" class="tblCell none">7</td>
<td id="cell8" class="tblCell none">8</td>
</tr>
<tr>
<td id="cell9" class="tblCell none">9</td>
<td id="cell10" class="tblCell none">10</td>
<td id="cell11" class="tblCell none">11</td>
<td id="cell12" class="tblCell none">12</td>
</tr>
<tr>
<td id="cell13" class="tblCell none">13</td>
<td id="cell14" class="tblCell none">14</td>
<td id="cell15" class="tblCell none">15</td>
<td id="cell16" class="tblCell none">16</td>
</tr>
</tbody>
</table>
CSS
.none{
background-color: #F3F5F6
}
.green{
background-color: green
}
Javascript代码
var count = 0;
$(".tblCell").click(function(){
if($("#"+this.id).hasClass("none")){
$("#"+this.id).addClass("green")
$("#"+this.id).removeClass("none")
count++;
}
else if($("#"+this.id).hasClass("green")) {
$("#"+this.id).addClass("none")
$("#"+this.id).removeClass("green")
count--;
}
console.log("Count Is : " + count);
});
答案 3 :(得分:0)
此代码效果很好。 ,并帮助你
<html>
<head>
<meta charset="utf-8">
<style>
td {
border: 2px solid #000;
padding: 20px;
}
</style>
</head>
<body>
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var counter = 0;
window.onclick = function(){clk(event);}
function clk(event){
var againClk = event.target.style.backgroundColor;
if(event.target.nodeName == "TD" && againClk != "green" ){
event.target.style.backgroundColor ="green";
x.innerHTML = "counter : " + (++counter);
}
}
</script>
</body>
</html>