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

学习用CRUD应用JavaScript代码优化建议咨询及新手每日合理编码时长疑问

Hey there! Great job building your first CRUD app—this is a solid start for a beginner. Let’s break down the improvements we can make to your code, and then tackle that question about daily coding time.


Code Improvement Suggestions

Let’s go through your code step by step to make it cleaner, safer, and more maintainable:

1. Eliminate Duplicate Function Calls

Right now you call getSaveData() twice—once upfront, then again in your if check. This wastes resources (double-reads from localStorage) and could cause redundant renders. Fix it by storing the result once:

const hasSavedData = getSaveData();
if (!hasSavedData) {
  console.log("No saved data found, Fetching new data");
  fetchData();
}

2. Replace innerHTML with DOM Methods

Using innerHTML to build HTML carries XSS security risks (if user input ever includes malicious code) and is less performant. Switch to creating elements directly with document.createElement:

function renderData(data) {
  posts_container.innerHTML = "";
  data.forEach((element, idx) => {
    // Build each post card with DOM methods
    const postCard = document.createElement('div');
    postCard.className = 'post-card';

    const titleDiv = document.createElement('div');
    titleDiv.className = 'post-title';
    titleDiv.textContent = element.title; // Avoids XSS risks

    const bodyDiv = document.createElement('div');
    bodyDiv.className = 'post-body';
    bodyDiv.textContent = element.body;

    const actionsDiv = document.createElement('div');
    actionsDiv.className = 'post-actions';

    // Add edit button with event listener (no inline onclick!)
    const editBtn = document.createElement('button');
    editBtn.className = 'edit-btn';
    editBtn.textContent = 'Edit';
    editBtn.addEventListener('click', () => editItem(idx));

    // Add delete button
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'delete-btn';
    deleteBtn.textContent = 'Delete';
    deleteBtn.addEventListener('click', () => deleteItem(idx));

    // Assemble the card
    actionsDiv.append(editBtn, deleteBtn);
    postCard.append(titleDiv, bodyDiv, actionsDiv);
    posts_container.appendChild(postCard);
  });
}

3. Improve Variable Naming & Reduce Global Scope

  • Rename variables to follow standard camelCase (e.g., title_input → titleInput)
  • Combine editId and globalIdx into a single object like currentEdit to keep related state together
  • Avoid overusing global variables where possible—for now, even just renaming globalData to postsData makes its purpose clearer

4. Add Form Validation

Right now users can submit empty titles or bodies. Add a quick check to prevent that:

form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const title = titleInput.value.trim();
  const body = bodyInput.value.trim();

  if (!title || !body) {
    alert('Please fill in both title and body!');
    return;
  }

  // Rest of your submit logic...
});

5. Enhance Error Handling

Your fetchData function has vague error handling. Give yourself (and users) clearer feedback:

async function fetchData() {
  try {
    const response = await fetch(fetchURL);
    if (!response.ok) {
      throw new Error(`Failed to load posts: HTTP status ${response.status}`);
    }
    postsData = await response.json();
    renderData(postsData);
  } catch (error) {
    console.error(error.message);
    posts_container.innerHTML = '<p>Oops! We couldn\'t load posts right now. Please try again later.</p>';
  }
}

6. Add UI Feedback for Edit Mode

Help users know they’re editing by updating the submit button text:

function editItem(index) {
  titleInput.value = postsData[index].title;
  bodyInput.value = postsData[index].body;
  currentEdit = { index, id: postsData[index].id };
  // Change button text to indicate edit mode
  saveBtn.textContent = 'Update';
}

// Reset button text after submission
form.addEventListener("submit", async (e) => {
  // ... submit logic ...
  form.reset();
  saveBtn.textContent = 'Save';
  currentEdit = null;
});

7. Polish LocalStorage Actions

  • When deleting saved data, reset your app state to match:
removeSaveBtn.addEventListener("click", () => {
  localStorage.removeItem("saveData");
  postsData = [];
  fetchData();
  alert('Saved data has been removed!');
});

Daily Coding Time for Beginners

As a new programmer, focus on consistency and quality over raw hours:

  • 1-3 hours of focused coding per day is ideal. Your brain needs time to absorb new concepts—forcing 8-hour sessions will lead to burnout and shallow learning.
  • Use the Pomodoro Technique: 25 minutes of coding, followed by a 5-minute break. Repeat this cycle to stay focused.
  • Mix coding with learning: Spend 30 minutes each day reviewing concepts (like array methods, DOM manipulation) or reading documentation alongside writing code.
  • Listen to your body: If you’re stuck or tired, step away. A walk or a snack can help you come back with fresh eyes.
  • Prioritize consistency over intensity: Coding 1 hour every day will help you progress faster than cramming 8 hours on weekends.

Keep up the great work—building CRUD apps is a fantastic way to learn core programming concepts. Don’t be afraid to experiment and make mistakes; that’s how we all learn!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 06:39:01