所以,基本上,我试图替换span的值,但点击
后会抛出一个错误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
classList
未定义,因为您没有通过span
&toggleEditMode
函数中的input
元素。这将解决您的错误,但您的应用程序仍然无法工作,因为在再次执行toggleEditMode
函数之前没有等待用户的输入。所以用户甚至没有时间来填写内容。
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);
};