错误:无法读取未定义的属性(读取“trim”)

问题描述 投票:0回答:1

我的网站上有 div,当我单击其中一个时,会出现一个该 div 特有的文本框。当我按下应该保存文本的“添加项目”按钮时,它在 addListItem 函数上给出了一个错误:

未捕获类型错误:无法读取未定义的属性(读取“trim”)

以下是我针对此案例的一些职能:

// Add a new list item
    function addListItem(shapeId) {
      const shape = $(`#${shapeId}`);
      const shapeInfo = shape.data("info");
      if (shapeInfo) {
        const shapeInput = shape.find(".shape-input");
        const newItem = shapeInput.val();
        if (newItem.trim() !== "") {
          if (!shapeInfo.items) {
            shapeInfo.items = [];
          }
          shapeInfo.items.push(newItem);
          shapeInput.val("");
          populateShapeList(shape);
          saveShapeData();
        }
      }
    }

    // Function to save shape data to local storage
    function saveShapeData() {
      const shapesData = [];
      $(".shape").each(function() {
        const shapeId = $(this).attr("id");
        const shapeData = {
          id: shapeId,
          top: $(this).position().top,
          left: $(this).position().left,
          width: $(this).width(),
          height: $(this).height(),
          items: $(this).data("info") ? $(this).data("info").items : []
        };
        shapesData.push(shapeData);
      });
      localStorage.setItem("shapes", JSON.stringify(shapesData));
    }

代码不完全是我的,据我所知,带有修剪功能的部分试图确定输入是否为空,但问题似乎出现在那里。我不是专业人士,如有错误请指正。

javascript html jquery local-storage
1个回答
0
投票
// Add a new list item
function addListItem(shapeId) {
  const shape = $(`#${shapeId}`);
  const shapeInfo = shape.data("info");
  if (shapeInfo) {
    const shapeInput = shape.find(".shape-input");
    const newItem = shapeInput.val();
    if (newItem && newItem.trim() !== "") {
      if (!shapeInfo.items) {
        shapeInfo.items = [];
      }
      shapeInfo.items.push(newItem);
      shapeInput.val("");
      populateShapeList(shape);
      saveShapeData();
    }
  }
}

// Function to save shape data to local storage
function saveShapeData() {
  const shapesData = [];
  $(".shape").each(function() {
    const shapeId = $(this).attr("id");
    const shapeData = {
      id: shapeId,
      top: $(this).position().top,
      left: $(this).position().left,
      width: $(this).width(),
      height: $(this).height(),
      items: $(this).data("info") ? $(this).data("info").items : []
    };
    shapesData.push(shapeData);
  });
  localStorage.setItem("shapes", JSON.stringify(shapesData));
}

我认为问题有时是 newItem 未定义,这就是为什么你会收到错误。 只需检查一个条件,例如 if (newItem && newItem.trim() !== "") 这次它将检查第一个 newItem 是否存在,然后才会执行下一个函数。 尝试更新的代码。我希望它能工作..

© www.soinside.com 2019 - 2024. All rights reserved.