После jquery removeClass обратный отсчет в любом случае начните снова - PullRequest
0 голосов
/ 26 марта 2019

Нажатием на div что-то происходит, а также я удаляю класс из div, так что ничего не происходит, если я снова нажимаю на div.Но хотя класс отсутствует, следующий щелчок запускает также функцию jQuery.

Я хочу нажать на кнопку, а затем происходит:

  • a.div будет прятаться через x секунд
  • b.другой div покажет через x секунд
  • c.запускается обратный отсчет, чтобы показать, когда произойдет изменение

Это будет прекрасно работать.

Если я сначала нажму на кнопку1, отсчет должен начаться (так и есть).
Если я снова нажму на кнопку1, обратный отсчет не должен начаться снова.
(Но это происходит - хотя я удаляю класс селектора первым щелчком мыши)

Как можно избежать, что обратный отсчет начинается снова?

$('.button1').click(function() {

  $('.output0').delay(10000).fadeOut(500);
  $('.output1').delay(10500).show(0);

});


$('.button1').click(function() {
  $('.button1').removeClass('button1');
});



(function($) {
  $.fn.countTo = function(options) {
    // merge the default plugin settings with the custom options
    options = $.extend({}, $.fn.countTo.defaults, options || {});

    // how many times to update the value, and how much to increment the value on each update
    var loops = Math.ceil(options.speed / options.refreshInterval),
      increment = (options.to - options.from) / loops;

    return $(this).each(function() {
      var _this = this,
        loopCount = 0,
        value = options.from,
        interval = setInterval(updateTimer, options.refreshInterval);

      function updateTimer() {
        value += increment;
        loopCount++;
        $(_this).html(value.toFixed(options.decimals));

        if (typeof(options.onUpdate) == 'function') {
          options.onUpdate.call(_this, value);
        }

        if (loopCount >= loops) {
          clearInterval(interval);
          value = options.to;

          if (typeof(options.onComplete) == 'function') {
            options.onComplete.call(_this, value);
          }
        }
      }
    });
  };

  $.fn.countTo.defaults = {
    from: 0, // the number the element should start at
    to: 100, // the number the element should end at
    speed: 1000, // how long it should take to count between the target numbers
    refreshInterval: 100, // how often the element should be updated
    decimals: 0, // the number of decimal places to show
    onUpdate: null, // callback method for every time the element is updated,
    onComplete: null, // callback method for when the element finishes updating
  };
})(jQuery);


$('.button1').click(function() {

  jQuery(function($) {
    $('.timer').countTo({
      from: 10,
      to: 0,
      speed: 10000,
      refreshInterval: 50,
      onComplete: function(value) {
        console.debug(this);
      }
    });
  });

});
.button {
  padding: 30px;
  background-color: red;
  width: 200px;
}

.output0 {
  padding: 30px;
  background-color: yellow;
  width: 200px;
}

.output1 {
  padding: 30px;
  background-color: green;
  width: 200px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="button1 button" style="">
  Button1 to show something after 10 seconds
</div>

<div class="output0" style="">
  I will hide after 10 seconds
</div>

<div class="output1" style="">
  I will show after 10 seconds
</div>

<div class="timer"></div>

Посмотреть на jsFiddle
Или здесь, на живой сайт

1 Ответ

0 голосов
/ 26 марта 2019

Проблема в том, что ваш элемент .button1 все еще имеет прослушиватель события click, даже если вы удалите из него класс.

Потенциальным решением было бы использование функции .one в jQuery. Это позволит запускать событие только один раз для каждого элемента для каждого типа события. Это потребует, чтобы ваши .click события были объединены в одну функцию следующим образом:

$('.button1').one('click', function(){

  $('.output0').delay(10000).fadeOut(500);
  $('.output1').delay(10500).show(0);

  jQuery(function($) {
        $('.timer').countTo({
            from: 10,
            to: 0,
            speed: 10000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
});

http://api.jquery.com/one/

...