P粉3889454322023-08-19 09:11:58
这里有一些问题
其中一些问题:
+
将其转换为数字或0(如果未定义),并使用条件链接运算符?.
来处理缺少的邮政编码const checkZones = () => { // 这里是一个更简单的fetch //fetch("{{ 'zones.json' | asset_url }}") // .then(response => response.json()) // .then(zones => updatePrice(zones)); updatePrice(zones) } const postcodeFormInput = document.querySelector("#postcodeForm input[type=text]"); const productTemplate = document.getElementById('ProductPrice-product-template'); const updatePrice = (zones) => { const postCode = postcodeFormInput.value; console.log("Input",postCode) const cost = +zones.find(({postcodes}) => postcodes.includes(postCode))?.cost; // 如果未找到则为0 if (!cost) return; // 未找到 const productPrice = +productTemplate.textContent; const newPrice = productPrice + cost; productTemplate.innerHTML = newPrice; }; document.getElementById("postcodeForm").addEventListener("submit", (e) => { e.preventDefault(); // 停止提交 checkZones() })
<form id="postcodeForm"> <input type="text"> <button type="submit">更新成本</button> </form> <span id="ProductPrice-product-template">0.00</span> <script> // 测试数据,在取消注释fetch时将其删除 const zones = [{ "name": "zone 1", "postcodes": [ "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10" ], "cost": 10.8 }, { "name": "zone 2", "postcodes": [ "test12", "test13", "test14", "test15", "test16", "test17", "test18", "test19", "test18", "test19", "test20" ], "cost": 16.8 } ]; </script>