点击一个div会发生一些事情,我也会从div中删除该类,这样如果我再次点击div就没有任何反应。但是虽然该类已经离开,但下一次单击也会启动jQuery函数。
我想要一个按钮点击然后发生:
这将很有效。
如果我先按下按钮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>
问题是你的.button1
元素仍然有一个click事件监听器,即使你从中删除了它。
一个潜在的解决方案是使用jQuery的.one
函数。这将仅允许每个事件类型的每个元素运行一次事件。它需要将你的.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);
}
});
});
});