使用JS和JSON以及简单的HTML表单来更新价格
<p>我正在尝试创建一个设置,在这个设置中,您可以输入邮政编码,提交表单,然后使用JavaScript检查邮政编码的前4个字符是否与某些JSON数据中的邮政编码匹配,如果匹配,则更改页面上的价格。这将用于Shopify网站,因此如果有关如何在其中实施它的任何帮助,将会很好。</p>
<p>目前,当我提交表单时,页面会刷新,但没有任何反应。</p>
<p>以下是我目前所拥有的,还处于早期阶段:</p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">async function checkZones() {
// const requestURL = "{{ 'zones.json' | asset_url }}";
// const request = new Request(requestURL);
//const response = await fetch(request);
// const zones = await response.json();
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
}
]
console.log(zones);
updatePrice()
}
function updatePrice(zone) {
const postcodeFormInput = document.querySelector('#postcodeForm input[type="text]"');
const postcodes = zone.postcodes;
for (const code of postcodes) {
if (postcodeFormInput.value.contains(code)) {
const productPrice = document.querySelector('#ProductPrice-product-template').textContent;
if (code === "test1") {
const newPrice = productPrice + zone.cost;
document.querySelector('#ProductPrice-product-template').innerHTML = newPrice;
}
}
}
}</pre>
<pre class="brush:html;toolbar:false;"><form onsubmit="checkZones()" id="postcodeForm">
<input type="text">
<button type="submit">Update Costs</button>
</form><span id="ProductPrice-product-template">0.00</span></pre>
<p><br /></p>
这里有一些问题
其中一些问题:
+将其转换为数字或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>