简体   繁体   中英

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. 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.

 $('#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. Starting an ID with a numeric value is invalid for CSS. You can do that with with class identifiers, but not IDs. I've changed your IDs in this example.

'#1' && '#2' && '#3' && '#4' && '#5' is equivalent to '#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.

You do not need to hard code all ids for a selection; we can select HTML elements as well.

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM