继续将 'undefined, undefined' 保存在本地存储中

Keep getting 'undefined, undefined' saved in local storage

我正在制作一个日程安排应用程序,其中包含从 0900-1700 的小时块,其中输入可以保存到本地存储中,然后在页面刷新时自动检索。我的代码目前有问题,它只在控制台中保存 'undefined, undefined',并且在页面刷新时不返回任何内容。任何帮助表示赞赏。谢谢!

HTML:

 <tr class="row" id="15">
            <th scope="time" id="hour15" class="time">15:00</th>
            <td><input type="text" class= "hourinput"/></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>
          <tr class="row" id="16">
            <th scope="time" id="hour16" class="time">16:00</th>
            <td><input type="text" class= "hourinput"/></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>

JS:

// Moment.js to auto-update time on webpage------------------------------------------//
var update = function () {
    date = moment(new Date());
    currentDay.html(date.format('dddd, MMMM Do YYYY, HH:mm:ss a'));
};

$(document).ready(function(){
    currentDay = $('#currentDay');
    update();
    setInterval(update, 1000);
});
// Add input to local storage-------------------------------------------------------//

$('.saveBtn').on('click', function () {
    // Get the values
    var hourinput = $(this).siblings('.hourinput').val();
    var hour = $(this).parent().attr('id');

    // Save data in local storage
    localStorage.setItem(hour, hourinput);
});

  $('#9 .hourinput').val(localStorage.getItem('9'));
  $('#10 .hourinput').val(localStorage.getItem('10'));
  $('#11 .hourinput').val(localStorage.getItem('11'));
  $('#12 .hourinput').val(localStorage.getItem('12'));
  $('#13 .hourinput').val(localStorage.getItem('13'));
  $('#14 .hourinput').val(localStorage.getItem('14'));
  $('#15 .hourinput').val(localStorage.getItem('15'));
  $('#16 .hourinput').val(localStorage.getItem('16'));
  $('#17 .hourinput').val(localStorage.getItem('17'));

您的 .saveBtn 元素没有兄弟姐妹。您需要遍历到 .row,然后找到其中的元素/值。

例如

$(".saveBtn").on("click", function () {
  const row = $(this).closest(".row") // see https://api.jquery.com/closest/

  // Get the values
  const hourinput = row.find(".hourinput").val();
  const hour = row.attr('id');

  // Save data in local storage
  localStorage.setItem(hour, hourinput);
});

仅供参考,您的 click 事件处理程序可以通过在容器级别进行侦听来提高效率(例如您的 <table>

$("table#hours").on("click", ".row[id] .saveBtn", function() {
  // etc
})

您还应该制作按钮 type="button" 以确保它们不会意外提交任何表单。