jQuery配方数量计算器



我想为一个食谱创建一个计算器,根据人数乘以数量。当前的脚本进行了一些计算,并用数量更新了跨度,但它产生了一些非常奇怪的东西。

第一个字段I定义人数(配方中的标准4人(

接下来的字段包含某物的数量(4人的标准数量(:

我怀疑一个问题是类";数量;这种情况已经存在好几次了。不知怎么的,我试着用.ech((从每个跨度数量类中获取有效值,但这根本不起作用。

jQuery(document).ready(function($) {
$("#people").change(function() {
$people = $(this).val();
$quantity = parseFloat($(".quantity").text());
$(".quantity").html($people * $quantity);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" value="4" id="people">
<p><span class="quantity">4</span> pieces of something</p>
<p><span class="quantity">200</span> g of butter</p>
<p><span class="quantity">500</span> ml of milk</p>

你是说这个

$(function() {
$("#people").on("input", function() {
const people = +$(this).val();
const base = +$(this).data("ppl");
$(".quantity").text(function() {
return people ? ($(this).data("qty") * ( people / base)).toFixed(0) : 0
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" value="4" data-ppl="4" id="people">
<p><span class="quantity" data-qty="4">4</span> pieces of something</p>
<p><span class="quantity" data-qty="200">200</span> g of butter</p>
<p><span class="quantity" data-qty="500">500</span> ml of milk</p>

使用对象:

const recipies = {
"Cheese cake": {
base: 4,
ingredients: ["4 of something", "200g of flour", "400g of cottage cheese", "2 spoons of sugar"]
},
"Chocolate cake": {
base: 4,
ingredients: ["8 of something", "400g of flour", "500g of chocolate", "4 spoons of sugar"]
}
}
$(function() {
const $recipe = $("#recipe");
const $ingredients = $("#ingredients");
// fill the select
Object.keys(recipies).forEach(key => $recipe.append(`<option value="${key}">${key}</option>`));
$(".inp").on("input", function() { // change people or recipe
$ingredients.empty();
const people = +$("#people").val();
if (people === 0) return
const recipe = recipies[$("#recipe").val()];
if (!recipe) return;
const base = recipe.base;
$ingredients.html(
recipe.ingredients.map(ingredient => {
let amount = ingredient.match(/d+/)[0];
let calc = (amount * people/base).toFixed(2);
if (parseInt(calc) == calc) calc = parseInt(calc); // remove decimals when not needed
return `<p>${ingredient.replace(amount,calc)}</p>`
})
)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="recipe" class="inp">
<option value="">Please select</option>
</select>
<input type="number" value="0" id="people" class="inp">
<div id="ingredients"></div>

最新更新