You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

预算应用开发:如何让渲染列表正确展示用户输入的数据?

Fixing Duplicate Rendering & Invalid ID Display in Your Budget App

Let's break down and fix the two main issues you're facing, plus a few hidden bugs causing unexpected behavior:

1. Why raw ID syntax is showing up in your output

Your createId function has a template string syntax error. You used $(new Date().getTime())} instead of ${new Date().getTime()} — the misplaced parenthesis and wrong $ placement are causing raw code to appear in your IDs.

Fixed ID generator:

const createId = () => `${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;

2. Why content is duplicating & rendering incorrectly

There are multiple issues in your DOM selection and render logic:

  • Broken HTML structure: You have nested <button> tags and unclosed <label> elements, which messes up the DOM and causes duplicate rendering.
  • Array-to-string conversion: map() returns an array of strings, but assigning it directly to innerHTML adds commas between entries and causes unexpected repeats. Use join('') to turn the array into a single HTML string.
  • Incorrect DOM selectors: Your el object has typos (e.g., el.number points to .end-date instead of .number) and conflicting class selections (the first <select> has both catagory and cashflow classes, so querySelector picks the wrong element).

Fixed DOM selector object & render function:

// Corrected DOM selector object
const el = {
  list: document.querySelector(".list"),
  cashflow: document.querySelector(".cashflow"),
  catagory: document.querySelector(".catagory:not(.cashflow)"), // Avoid class conflict
  label: document.querySelector(".label"),
  startDate: document.querySelector(".start-date"),
  endDate: document.querySelector(".end-date"),
  number: document.querySelector(".number"), // Fixed typo here
};

// Fixed render function
function renderList() {
  // Use join('') to concatenate map results into one HTML string
  el.list.innerHTML = budgetArray.map(function(data, i) {
    return `<div class="entry">
      <div class="list-item"> <!-- Renamed to avoid conflict with outer .list container -->
        <button onclick="deleteItem(event, ${i})" class="Archive" data-id="${data.id}">
          <img src="../resources/Images/archive.png" alt="Archive">
        </button>
        <button onclick="editItem(event, ${i})" class="edit" data-id="${data.id}">
          <img src="../resources/Images/edit.png" alt="Edit">
        </button>
        <div class="input" data-id="${data.id}"></div>
        <label class="print date">${data.startDateNew} - ${data.endDateNew}</label>
        <label class="print income">${data.cashflowNew}</label>
        <label class="print cata">${data.catagoryNew}</label>
        <label class="print reason">${data.labelNew}</label>
        <label class="print amount">${data.numberNew}</label>
      </div>
    </div>`;
  }).join(''); // Critical step to eliminate commas and duplicates

  // Clear form inputs after rendering
  el.cashflow.value = "";
  el.catagory.value = "";
  el.label.value = "";
  el.startDate.value = "";
  el.endDate.value = "";
  el.number.value = "";
}

3. Additional Fixes for Persistence & Form Logic

  • LocalStorage requires stringification: You can't store arrays directly in localStorage — use JSON.stringify and JSON.parse to save/retrieve data. Also define a storage key:
const STORAGE_KEY = "budgetEntries";

// Fixed storage function
function storedEntry() {
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(budgetArray));
}

// Load saved entries on page load
window.addEventListener('load', () => {
  const savedEntries = localStorage.getItem(STORAGE_KEY);
  if (savedEntries) {
    budgetArray = JSON.parse(savedEntries);
    renderList();
  }
});
  • Form validation guard: Your click handler doesn't stop execution if validation fails — add a return to prevent empty entries from being added:
budgetButton.addEventListener("click", () => {
  if (!label.value || !startDate.value || !endDate.value || !num.value) {
    alert("Please make sure all inputs are filled");
    return; // Halt execution if validation fails
  }
  budgetArray.push(makeNewBudget());
  renderList();
  storedEntry();
});

After applying these fixes, your app will:

  • Generate valid IDs without raw syntax
  • Render entries cleanly without duplicates
  • Save and load entries from localStorage
  • Clear form inputs automatically after adding an entry

内容的提问来源于stack exchange,提问作者Sheldon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 22:04:08