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

mu0hgdu0  于 2023-10-17  发布在  jQuery
关注(0)|答案(2)|浏览(171)

我在我的网站上有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));
    }

代码不完全是我的,据我所知,与修剪功能的一部分是试图决定是否输入是空的,但问题似乎出现在那里。如果我错了请纠正我,我不是Maven。

62o28rlo

62o28rlo1#

// 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是否存在,然后只执行下一个。尝试更新的代码.我希望它会工作..

anauzrmj

anauzrmj2#

下面的示例将生成一个随机形状并将其添加到本地存储中的形状中。
渲染时,将从本地存储中检索形状。
将代码分成模块化函数可能有助于可读性和可维护性。我创建了一个将形状对象转换为元素的函数,另一个函数则相反。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>jQuery + localStorage</title>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
      integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <style>
      *,
      *:before,
      *:after {
        box-sizing: border-box;
      }
      html,
      body {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
      body {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 1rem;
        padding: 1rem;
      }
      .shape-list {
        position: relative;
        background: #ddd;
        flex: 1;
        width: 100%;
      }
      .shape {
        position: absolute;
        border: thin solid red;
      }
      .actions {
        display: flex;
        justify-content: center;
        gap: 0.5rem;
      }
    </style>
    <script>
      $(function () {
        populateShapeList();

        $('form[name="add-shape"]')
          .find('[name="shape"]')
          .val(JSON.stringify(randomShape(), null, 2));

        $('form[name="add-shape"]').on("submit", (e) => {
          e.preventDefault();
          addListItem($(e.target).find('[name="shape"]'));
        });

        $("#clear-btn").on("click", (e) => {
          const $input = $(e.target).closest("form").find('[name="shape"]');
          clearShapes();
          populateShapeList();
          $input.val(JSON.stringify(randomShape(), null, 2));
        });
      });

      // Add a new list item
      function addListItem($input) {
        const shape = $input.val();
        if (shape.trim().length > 0) {
          saveShape(JSON.parse(shape));
          populateShapeList();
          $input.val(JSON.stringify(randomShape(), null, 2));
        }
      }

      function populateShapeList($shape) {
        $(".shape-list").empty().append(restoreShapes().map(fromObject));
      }

      function randomShape() {
        const $shapeList = $(".shape-list");
        const maxWidth = $shapeList.outerWidth();
        const maxHeight = $shapeList.outerHeight();
        let top = randInt(0, maxHeight);
        let left = randInt(0, maxWidth);
        const width = randInt(10, 300);
        const height = randInt(10, 300);
        if (top + height > maxHeight) {
          top -= maxHeight - height; // Nudge up
        }
        if (left + width > maxWidth) {
          left -= maxWidth - width; // Nudge left
        }
        return {
          id: `box${restoreShapes().length + 1}`,
          top: top,
          left: left,
          width: width,
          height: height,
          items: [],
        };
      }

      function toObject($shape) {
        return {
          id: $shape.attr("id"),
          top: $shape.position().top,
          left: $shape.position().left,
          width: $shape.width(),
          height: $shape.height(),
          items: $shape.data("info") ? $shape.data("info").items : [],
        };
      }

      function fromObject(shape) {
        return $("<div>")
          .attr("id", shape.id)
          .addClass("shape")
          .css({
            top: `${shape.top}px`,
            left: `${shape.left}px`,
            width: `${shape.width}px`,
            height: `${shape.height}px`,
          })
          .data("info", { items: shape.items });
      }

      function saveShape(shape) {
        saveShapes(restoreShapes().concat(shape));
      }

      function saveShapes(shapes) {
        localStorage.setItem("shapes", JSON.stringify(shapes));
      }

      function restoreShapes() {
        return JSON.parse(localStorage.getItem("shapes") ?? "[]");
      }

      function clearShapes() {
        return localStorage.clear("shapes");
      }

      function randInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
    </script>
  </head>
  <body>
    <h1>jQuery + localStorage</h1>
    <form name="add-shape">
      <textarea class="shape-input" name="shape" rows="10" cols="40"></textarea>
      <div class="actions">
        <button id="add-btn" type="submit">Add</button>
        <button id="clear-btn" type="button">Clear</button>
      </div>
    </form>
    <div class="shape-list"></div>
  </body>
</html>

相关问题