You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击笔记标题时切换对应笔记内容的显示隐藏状态

解决方案

你可以通过DOM相邻节点属性直接定位到对应内容元素,同时补全切换显示/隐藏的逻辑即可,修改后的代码如下:

const titles = document.querySelectorAll(".note-title");

titles.forEach(function(title) {
  title.addEventListener("click", () => {
    // 取当前点击标题的下一个同级元素,就是对应的内容输入框
    const currentContent = title.nextElementSibling;
    // 切换显示状态
    currentContent.style.display = currentContent.style.display === "none" ? "inline-block" : "none";
  });
});

补充说明

  • 如果后续结构调整,标题和内容之间可能插入其他元素,可以改用title.parentElement.querySelector('.note-content')选中同个笔记容器内的内容元素,不受节点顺序影响,兼容性更强。
  • 你给出的HTML结构中<input class="note-content">Note content</input>写法不规范,input为单标签,内容需要写在value属性中;如果需要多行文本输入,建议替换为<textarea class="note-content">Note content</textarea>。
  • 如果涉及动态新增笔记的场景,上面的写法仅能给页面加载时已存在的标题绑定事件,新增的笔记需要在插入DOM时单独绑定事件,也可以直接使用事件委托绑定到父容器上,无需每次新增重复绑定:
document.querySelector('.notes-list').addEventListener('click', (e) => {
  if(e.target.classList.contains('note-title')) {
    const currentContent = e.target.nextElementSibling;
    currentContent.style.display = currentContent.style.display === "none" ? "inline-block" : "none";
  }
});

内容的提问来源于stack exchange,提问作者Ashley Slaney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 11:45:04