我有一小段 jQuery 代码,它根据给定的服务计算食谱成分,但在某处它无法正常工作。
我的代码是这样的:
Serving: <input type="text" name="serving" class="serving" value="5" /> persons
<input type="hidden" id="previousServing" value="5"/>
<h3>ingredients</h3>
<ul class="ingredients">
<li class="ingredient">
<span class="amount">1</span> cups
<span class="name"><a href="http://www.mysite.com/ingredient/yogurt/">yogurt</a></span>
</li>
<li class="ingredient">
<span class="amount">2</span> tbsp
<span class="name"><a href="http://www.mysite.com/ingredient/yogurt/">chillies</a></span>
</li>
<li class="ingredient">
<span class="amount">3</span> pieces
<span class="name"><a href="http://www.mysite.com/ingredient/yogurt/">butter</a></span>
</li>
</ul>
$(function() {
$('.serving').bind('keyup', function(event) {
var previousValue = parseFloat($("#previousServing").val());
var newValue = parseFloat($(event.target).val());
if (previousValue && newValue) {
$('.ingredient').each(function(index, elem) {
var ingredientNow = $('.amount', elem);
var oldIngredientAmount = ingredientNow.text();
var newIngredientAmount = oldIngredientAmount * newValue / previousValue;
ingredientNow.text(newIngredientAmount);
});
$('#previousServing').val(newValue);
}
});
});
http://jsfiddle.net/vansimke/tLWpr/
问题:
- 将服务更改为 1.5,它将给出无限的小数位
- 将服务设置回原始(5),小数不会消失
要求:没有小数或四舍五入到绝对两位数,即 2.08 应为 2.00。
感谢期待。