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

如何获取表单元素ID并关联存储状态以控制按钮样式?

Let's fix your code step by step—you're so close, but a couple of tiny bugs are throwing things off! Here's what's going wrong and how to fix it:

1. Fix the initial() Function (Setting Initial Button States)

Your current code tries to get the form's element count with document.getElementById("myForm").length, but the <form> element itself doesn't have a length property. You need to target the elements collection inside the form instead. Also, it's smart to check if an element actually has an ID before storing it in sessionStorage (to avoid errors with form elements that don't have IDs).

Here's the corrected initial() function:

function initial() {
  // Only run this if we haven't initialized before
  if (localStorage.getItem("run") === null) {
    const form = document.getElementById("myForm");
    // Get the actual number of elements in the form
    const totalElements = form.elements.length;

    for (let i = 0; i < totalElements; i++) {
      const element = form.elements[i];
      // Skip elements without an ID to avoid invalid storage entries
      if (element.id) {
        sessionStorage.setItem(element.id, "false");
      }
    }

    // Mark initialization as done so we don't run it again
    localStorage.setItem("run", "true");
  }
}

2. Fix the loader() Function (Styling Buttons Based on State)

The biggest issue here is the return statements inside your loop—they make the loop exit after the first element, so only the first button gets styled. You need to remove those returns so every element gets processed. Also, we can skip re-querying the element with getElementById since we already have a direct reference from form.elements[i].

Here's the fixed loader() function:

function loader() {
  const form = document.getElementById("myForm");
  const totalElements = form.elements.length;

  for (let i = 0; i < totalElements; i++) {
    const element = form.elements[i];
    if (!element.id) continue; // Skip elements without an ID

    const status = sessionStorage.getItem(element.id);
    // Set background color based on the stored status
    if (status === "true") {
      element.style.backgroundColor = "green";
    } else {
      element.style.backgroundColor = "red";
    }
  }
}

3. Make Sure the Functions Run When the Page Loads

You need to trigger these functions after the page's DOM is fully loaded (so the form exists before we try to access it). Add this at the end of your script:

// Run initialization and styling once the page is ready
document.addEventListener("DOMContentLoaded", () => {
  initial();
  loader();
});

Quick Recap of Key Fixes

  • Initialization: Used form.elements.length to get the correct number of form elements, and added a check for valid IDs.
  • Loader: Removed return statements so all elements are processed, and used direct element references for better performance.
  • Trigger: Wrapped function calls in DOMContentLoaded to avoid errors from trying to access elements before they exist.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:51:50