[英]How to popup an alert when every cell in a table has been clicked?
If all the cells in my table have been clicked, I want to pop up an alert.如果我的表格中的所有单元格都被点击,我想弹出一个警报。
<td id="1" onclick="this.style.backgroundColor = 'Red';">1</td>
<td id="2" onclick="this.style.backgroundColor = 'Red';">2</td>
<td id="3" onclick="this.style.backgroundColor = 'Red';">3</td>
<td id="4" onclick="this.style.backgroundColor = 'Red';">4</td>
<td id="5" onclick="this.style.backgroundColor = 'Red';">5</td>
(I'm making the background red so that I know it has been clicked). (我将背景设为红色,以便我知道它已被点击)。 This is the script that I've been trying to get to work:
这是我一直试图开始工作的脚本:
<script>
$(document).ready(function () {
$('#1' && '#2' && '#3' && '#4' && '#5' ).click( function() {
alert('Bingo!'); });
});
</script>
If I click on cell number 5 right away, the alert pops up.如果我立即单击第 5 个单元格,则会弹出警报。 What I want is when every cell is already clicked, only then should the alert show up.
我想要的是当每个单元格都被点击时,只有这样警报才会出现。
If you're wanting to set each cell to have a red background individually on click it would be done like this and will alert after all 5 have been clicked.如果您想在单击时将每个单元格设置为单独具有红色背景,则可以这样做,并在单击所有 5 个单元格后发出警报。
$('#one, #two, #three, #four, #five').click( function() { $(this).toggleClass("redbg"); if($('.redbg').length == 5) alert('Bingo!'); });
.redbg { background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td id="one">1</td> <td id="two">2</td> <td id="three">3</td> <td id="four">4</td> <td id="five">5</td> </tr> </table>
Also, as TJ Crowder pointed in the comments below.此外,正如 TJ Crowder 在下面的评论中指出的那样。 Starting an ID with a numeric value is invalid for CSS.
以数值开头的 ID 对 CSS 无效。 You can do that with with class identifiers, but not IDs.
您可以使用类标识符来做到这一点,但不能使用 ID。 I've changed your IDs in this example.
在这个例子中,我已经更改了您的 ID。
'#1' && '#2' && '#3' && '#4' && '#5'
is equivalent to '#5'. '#1' && '#2' && '#3' && '#4' && '#5'
等价于 '#5'。 &&
on strings doesn't work that way. &&
在字符串上不起作用。
What you probably want to do is something like watch all of them for click, change the class on click to 'clicked', and then check that 5 cells have the 'clicked' class.您可能想要做的是观看所有这些点击,将点击类更改为“点击”,然后检查 5 个单元格是否具有“点击”类。
You do not need to hard code all ids for a selection;您不需要为选择对所有 id 进行硬编码; we can select HTML elements as well.
我们也可以选择 HTML 元素。
<!DOCTYPE html>
<html>
<head>
<style>
.bgColor {
background-color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("td").click(function(){
$(this).toggleClass("bgColor");
if($('.bgColor').length == 5)
alert('Bingo!');
});
});
</script>
</head>
<body>
<table>
<tr>
<td id="1">1</td>
<td id="2">2</td>
<td id="3">3</td>
<td id="4">4</td>
<td id="5">5</td>
</tr>
</table>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.