2016-05-31 138 views
0

我试图每次增加计数器,但是当点击html时,计数器会像+1,+ 2,+ 3,+ 4一样呈指数级增长。计数器递增成倍增加

Gif of it happening

$('.dates').click(function(){ 
     $('#output').html(function(i, val) { return val*1+1 }); 
}); 

HTML:

<div id="output">0</div> 

心动画代码:

var rand = Math.floor(Math.random() * 100 + 1); 
    var flows = ["flowOne", "flowTwo", "flowThree"]; 
    var colors = ["colOne", "colTwo", "colThree", "colFour", "colFive", "colSix"]; 
    var timing = (Math.random() * (1.3 - 0.3) + 1.6).toFixed(1); 
    // Animate Particle 
    $('<div class="particle part-' + rand + ' ' + colors[Math.floor(Math.random() * 6)] + '" style="font-size:' + Math.floor(Math.random() * (30 - 22) + 22) + 'px;"><i class="fa fa-heart-o"></i><i class="fa fa-heart"></i></div>').appendTo('.particle-box').css({ animation: "" + flows[Math.floor(Math.random() * 3)] + " " + timing + "s linear" }); 
    $('.part-' + rand).show(); 
    // Remove Particle 
    setTimeout(function() { 
     $('.part-' + rand).remove(); 
    }, timing * 1000 - 100); 
  1. 为什么会成倍递增?
  2. 我该如何让它每次增加1?像0,1,2,3,4
+0

你可以在JSFiddle上重现这个吗? –

+0

post html请 –

+2

它运作良好https://jsfiddle.net/v58dfs8u/我认为你多次绑定你的事件 –

回答

0

也许它正在考虑它作为字符串。使用parseInt解析值为整数,而不是使用字符串连接:

$('.dates').click(function() { 
    $('#output').html(function(i, val) { 
    return parseInt(val, 10) + 1; 
    }); 
}); 

工作片段:

$('.dates').click(function() { 
 
    $('#output').html(function(i, val) { 
 
    return parseInt(val, 10) + 1; 
 
    }); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" class="dates">Click</a> 
 
<div id="output">0</div>

+0

'val * 1'会将val转换为数字,所以这不是问题。然而使用'parseInt'确实更明确。 – floribon

+0

工作片段以某种方式阻止其下方的心脏动画代码 – user3421197

+0

@ user3421197除非您发布了完整的代码,否则您希望我们理解并解决您的问题? –

2

最有可能的,你注册一个新的click事件侦听每当你点击。

请检查并发布围绕行$('.dates').click(...)的代码。

请确保在代码中仅调用一次该行,而不是稍后再调用该行。

+0

是的。确实如此。 –