JavaScript:如何为带双值的复选框生成含名称与费用的li元素?
解决方案
要解决名称与费用关联的问题,核心是让复选框的选中状态同时携带名称和费用信息,再在渲染时对应展示。具体修改步骤如下:
1. 给复选框添加费用存储属性
在每个复选框的HTML代码中,通过data-price自定义属性存储对应费用:
<!-- Profile 复选框 --> <input id="profile-checkbox" type="checkbox" value="Custom profile" name="add-ons" onclick="getAddons()" data-price="+$1/mo" class="w-5 h-5 mr-2 text-blue-600 bg-gray-100 border-light-gray rounded" /> <!-- Online 复选框 --> <input id="online-checkbox" type="checkbox" value="Online service" name="add-ons" onclick="getAddons()" data-price="+$2/mo" class="w-5 h-5 mr-2 text-blue-600 bg-gray-100 border-light-gray rounded" /> <!-- Storage 复选框 --> <input id="storage-checkbox" type="checkbox" value="Extra storage" name="add-ons" onclick="getAddons()" data-price="+$2/mo" class="w-5 h-5 mr-2 text-blue-600 bg-gray-100 border-light-gray rounded" />
2. 修改复选框值的存储逻辑
更新getAddons函数,不再只存储名称,而是存储包含名称+费用的对象:
// Step 3, add-ons function getAddons() { let checkboxes = document.getElementsByName("add-ons"); addonsResult = []; for (let i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { // 存入包含名称和费用的对象 addonsResult.push({ name: checkboxes[i].value, price: checkboxes[i].dataset.price }); } } }
3. 更新结果页渲染逻辑
修改setResultsPage函数,读取对象中的名称和费用,同时完善DOM结构(添加费用元素到列表项中):
function setResultsPage() { // 先清空现有列表,避免重复渲染 addonsResultList.innerHTML = ''; addonsResult.forEach(function (addon) { const li = document.createElement("li"); const pName = document.createElement("p"); const pAmount = document.createElement("p"); const nameText = document.createTextNode(addon.name); const priceText = document.createTextNode(addon.price); li.classList.add("flex", "justify-between"); pName.appendChild(nameText); pName.classList.add("text-cool-gray", "text-sm"); pAmount.appendChild(priceText); pAmount.classList.add("text-sm", "text-marine-blue"); // 将名称和费用元素都添加到列表项 li.appendChild(pName); li.appendChild(pAmount); addonsResultList.appendChild(li); }); }
内容的提问来源于stack exchange,提问作者Ninety9Balloons
相关产品推荐
相关产品推荐

