javascript - 我试图一键挂起 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
解决方案
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);
};
推荐阅读
- angular - 如何测试服务模拟中可观察的变化?
- sql - Oracle时间戳问题转换日期
- json - Aps.net 核心 Razor 页面 [FromBody] Ajax 帖子模型始终为空
- mule-esb - 为什么 ESB 应用程序在部署期间尝试获取“'mule-tracking-ee.xsd'”时会生成警告?
- google-apps-script - Google API 返回响应 200 空 JSON
- html - 如何将搜索过滤器添加到角度的选择选项
- vue.js - 在 HTTPS 中运行 Visual Studio 默认的 Vue 项目
- javascript - 从数据属性中获取值到数组中
- c - C中实现mac地址表项老化的数据结构
- pandas - 使用 Airflow 进行多步 Pandas 处理