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

Bootstrap模态框营业时间输入重复存储问题求助

问题修复:营业时间重复存储的问题

问题根源

  1. 遍历逻辑错误:保存时遍历的是单个时间输入框(timeInputs),但每次都通过getElementById固定获取第一行的时间值,导致每遍历一个input就重复添加一次第一行的时间。
  2. 时间组的遍历单位错误:应该以每一行的时间组(包含开始+结束时间)为单位遍历,而不是单个输入框。

修复方案

修改Speichern按钮的点击事件逻辑,改为按时间行(.row)遍历,从每一行中直接获取对应的开始和结束时间输入框的值:

document.getElementById("Speichern").addEventListener("click", function (event) {
  event.preventDefault();
  days.forEach((day) => {
    // 先检查是否勾选了闭店
    const isClosed = document.getElementById(`${day}Checkbox`).checked;
    if (isClosed) {
      openingHours[day.toLowerCase()] = "Geschlossen";
      return;
    }

    const timeRows = document.querySelectorAll(`#${day}Times .row`);
    const timeRanges = [];

    timeRows.forEach((row) => {
      // 从当前行中获取开始和结束时间输入框
      const startTimeElement = row.querySelector('input[type="time"]:first-of-type');
      const endTimeElement = row.querySelector('input[type="time"]:last-of-type');
      
      const startTime = startTimeElement?.value;
      const endTime = endTimeElement?.value;

      if (startTime && endTime) {
        timeRanges.push({ begin: startTime, ende: endTime });
      }
    });

    openingHours[day.toLowerCase()] = timeRanges.length > 0 ? timeRanges : "Geschlossen";
  });

  const formattedOpeningHours = JSON.stringify(openingHours, null, 2);
  document.getElementById("ausgabe").textContent = formattedOpeningHours;
  document.getElementById("openhours_2").value = formattedOpeningHours;
  $("#openhours").modal("hide");
});

额外优化(可选)

新增时间行时,避免重复的name属性(虽然不影响功能,但更规范),可以给新增的input添加带索引的name,同时去掉无效的for关联:

// 在addTimeButton的点击事件里修改newRow.innerHTML
newRow.innerHTML = `
  <div class="col-6">
    <label>Starzeit:</label>
    <input type="time" class="form-control" name="${day}StartTime_${rowCount}" value="">
  </div>
  <div class="col-6">
    <label>Endzeit:</label>
    <input type="time" class="form-control" name="${day}EndTime_${rowCount}" value="">
  </div>
`;

修复后效果

当周日添加两行时间(比如12:00-18:00和19:00-22:00),输出会变为:

{
  "montag": "Geschlossen",
  "dienstag": "Geschlossen",
  "mittwoch": "Geschlossen",
  "donnerstag": "Geschlossen",
  "freitag": "Geschlossen",
  "samstag": "Geschlossen",
  "sonntag": [
    { "begin": "12:00", "ende": "18:00" },
    { "begin": "19:00", "ende": "22:00" }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:54:58