首页 > 解决方案 > 我试图一键挂起 2 个功能,但出现错误,我做错了什么?

问题描述

因此,基本上,我正在尝试替换跨度的值,但是单击后会引发错误

const addListenerToEditButtons = (arr) => {
        const updatedButtons = document.querySelectorAll('.container-buttons__update');
        updatedButtons.forEach((button, index) => {
            button.addEventListener('click', (e) => {
                const targetSpan = e.target.parentElement.parentElement.parentElement.children[3].children[0];
                const targetInput = e.target.parentElement.parentElement.parentElement.children[3].children[1];
                toggleEditMode(targetSpan, targetInput);
                editNote(arr, index, targetSpan, targetInput);
            })
        })
    }
    
    const toggleEditMode = (span, input) => {
        if (input.classList.contains(HIDE_ELEMS)) {
            span.classList.add(HIDE_ELEMS);
            input.classList.remove(HIDE_ELEMS);
            return
        }
        span.classList.remove(HIDE_ELEMS);
        input.classList.add(HIDE_ELEMS);
    }
    
    const editNote = (arr, index, span, input) => {
    
        arr.filter((item, i) => {
            if (i === index && input.value !== '') {
                item.content = input.value;
                return
            }
            toggleEditMode();
        })
        showAllNotes(arr);
    }

我收到一个错误:Uncaught TypeError: Cannot read properties of undefined (reading 'classList')

这是你可以测试我的代码:https ://codesandbox.io/s/winter-silence-yjxo3?file=/package.json

标签: javascript

解决方案


classList未定义,因为您没有在函数中传递span&input元素。这将解决您的错误,但您的应用程序将无法正常工作,因为您在再次执行该功能toggleEditMode之前无需等待用户的输入。toggleEditMode所以用户甚至没有时间填写一些东西。

在我看来,等待用户输入是违反 JavaScript 原则的。更好的解决方案是将输入侦听器附加到所有输入元素,如下所示:

const addListenerToEditButtons = (arr) => {
  const updatedButtons = document.querySelectorAll(
    ".container-buttons__update"
  );

  updatedButtons.forEach((button, index) => {
    const targetSpan =
        button.parentElement.parentElement.children[3]
            .children[0];
    const targetInput = button.parentElement.parentElement.children[3]
        .children[1];

    targetInput.addEventListener("input", (evt) => {
      targetSpan.innerText = evt.target.value; // here you set the span to the value of the input. You would probably want to store it somewhere here.
    });

    button.addEventListener("click", (e) => {
      toggleEditMode(targetSpan, targetInput); // here you make the input field visible when the edit button is clicked.
    });
  });

然后在您的toggleEditMode函数中,您还可以将现有文本放在输入字段中,并可能在其上自动聚焦。如果您只想在用户再次单击编辑按钮时保存该值,则可以这样做:

const toggleEditMode = (span, input) => {
  if (input.classList.contains(HIDE_ELEMS)) {
    span.classList.add(HIDE_ELEMS);
    input.classList.remove(HIDE_ELEMS);
    input.value = span.innerText;
    input.focus(); // so that the input field can automatically be typed into.
    return;
  }
  span.classList.remove(HIDE_ELEMS);
  input.classList.add(HIDE_ELEMS);
};

推荐阅读