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
217 views
in Technique[技术] by (71.8m points)

jquery - Count the number of times a button appears

I am trying to count the number of times that the fadeToggle button appears and include it in <p> paragraph element as text.

$(function () {
  var box = $("#box");
  var para = $("#p");
  var count = 0;
  for (var i = 0; i < 10; i++) {
    function toggleBox(i) {
      box.fadeToggle(500, function () {
        count++;
        para.text() = count(i);
      });
    }

    toggleBox(i);
  }
});

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

1 Answer

0 votes
by (71.8m points)
  • Its not a good thing to add a function inside a for loop like you did.. it will be better to put your fade animation inside a function then call the function inside of it after the fadeIn complete it will create the loop till reach the max_count
  • Also in jquery use para.text(count) instead of para.text() = count(i);

With fadeToggle the action is happen after element show and after hide

$(function () {
  var box = $("#box");
  var para = $("#p");
  var count = 1;
  var max_count = 10;
  toggleBox(box , para , count , max_count);
});

function toggleBox(box_selector , para_selector , count , max_count) {
  $(box_selector).fadeToggle(500, function () {
    $(para_selector).text(count);
    if(count < max_count){
      toggleBox(box_selector , para_selector , count + 1 , max_count);
    }
  });
}
#box{
  background : red;
  width : 100px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"></div>
<p id="p"></p>

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

...