Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

Jquery onclick toggleClass - three clicks required instead of two

I need a cell to have three colors : first loaded by the script, second ny clicking on the cell and third by clicking on one more time. And if I click again I get the first color back.

I wrote this :

<head>
</head>
<body>
<table border='2' cellpadding='20' align='center'>
    <tbody>
    <tr>
        <td class="switch">1</td>
        <td class="switch">2</td>
        <td class="switch">3</td>
    </tr>
    </tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
    $('.switch').click(function() {
        $(this).toggleClass('highlight');
        $(this).click(function() {
            $(this).toggleClass('highlight2');
        })
        $(this).click(function() {
            $(this).toggleClass('switch');
        })
    })
</script>
<style>
    .highlight {
        background-color: #ffff00;
    }
    .highlight2 {
        background-color: red;
    }
</style>
</body>

You can see how it works : jsfiddle

My problem is that the first two clicks work fine (the color change) but the third is useless and the fourth work as the third should (get the color back to the beginning).

I need to have only three clicks.

question from:https://stackoverflow.com/questions/65945358/jquery-onclick-toggleclass-three-clicks-required-instead-of-two

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am not sure I understood your problem, but here is something to start with:

    $(document).ready(function () {
      var i = 0;
        $('.combi').on('click', function () {
          i += 1;
          if (i == 1) {
            $(this).toggleClass('highlight');
          } else if (i == 2) {
            $(this).toggleClass('highlight2');
          } else {
            $(this).removeClass();
            i = 0;
          }
        })
    })
    .highlight {
      background-color: #ffff00;
    }

    .highlight2 {
      background-color: red;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <table border='2' cellpadding='5' align='center'>
    <tbody>
      <tr>
        <td class="combi">1</td>
      </tr>
      <tr>
        <td class="combi">8</td>
      </tr>
      <tr>
        <td class="combi">15</td>
      </tr>
    </tbody>
  </table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...