如何实现点击按钮触发jQuery食谱配料数量计算功能?
问题解决:点击按钮触发食谱配料计算
核心问题分析
你的代码存在三个关键错误导致按钮点击无响应:
- 按钮选择器不匹配:JS中使用类选择器
.js-calcService,但HTML按钮的属性是id="js-calcService",需改用ID选择器#js-calcService - dataset属性大小写错误:HTML中是
data-baseValue,对应DOM的dataset属性应为驼峰式baseValue,而非全小写的basevalue - 输入值类型问题:输入框获取的值是字符串,直接相乘可能出现字符串拼接而非数值计算,需要转为数字类型
修改后的完整代码
JavaScript代码
// Recipe calculator with jquery function computeServing(serving) { // 转换为数字,避免字符串拼接 const servingNum = Number(serving); $('.js-recipeIngredient').each(function(index, item) { // 修正dataset属性名,使用驼峰式baseValue const baseValue = Number(item.dataset.baseValue); $(item).children('span').html(baseValue * servingNum); }) } $('#servingInput').on('change', function() { computeServing($(this).val()) }) // 修正按钮选择器,用ID选择器#js-calcService $('#js-calcService').on('click', function() { const currentServing = $('#servingInput').val(); computeServing(currentServing); }) // 初始化计算 computeServing(4);
HTML代码(仅确认按钮ID匹配)
<h3>Recipe</h3> <div> <label for="serving">Portions :</label> <input type="number" id="servingInput" value="4"> <button id="js-calcService">Portionen</button> <div class="Recipe-IngredientList"> <div class="Recipe-Ingredient js-recipeIngredient" data-baseValue="100">Farine : <span></span>g</div> <div class="Recipe-Ingredient js-recipeIngredient" data-baseValue="2">Oeuf : <span></span></div> <div class="Recipe-Ingredient js-recipeIngredient" data-baseValue="150">Lait : <span></span>mL</div> <div class="Recipe-Ingredient js-recipeIngredient" data-baseValue="50">Lardon : <span></span>g</div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
CSS代码(保持不变)
.Recipe-IngredientList { width: 250px; border: 1px solid #777; border-radius: 3px; padding: 5px; margin-top: 5px; } .Recipe-Ingredient { border-bottom: 1px solid black; padding: 5px 0; } .Recipe-Ingredient:last-child { border-bottom: none; } .Recipe-Ingredient span { font-weight: 600; }
额外优化说明
- 加入
Number()类型转换,确保数值计算的正确性;若需进一步容错,可添加if (!isNaN(servingNum))判断,避免空值或非数字输入导致NaN显示 - 移除按钮事件中冗余的
$('#servingInput').val(currentServing)代码,该行无实际业务作用
内容的提问来源于stack exchange,提问作者Christian Mazilu
相关产品推荐
相关产品推荐

