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

JavaScript开发笔记应用时模态框无法展示对应笔记内容问题求助

问题根源

你写的代码里,点击「查看更多」时模态框的内容是直接读取当前输入框的value,没有和对应行的笔记内容绑定,所以才会出现输入框清空后模态框内容也变化的问题。

实现逻辑

  1. 新增全局数组存储所有笔记的完整内容,添加笔记时把内容推入数组
  2. 渲染表格行时做2个处理:
    • 表格内仅展示截断后的短文本(超过设定长度的话加省略号)
    • 给每一行绑定对应数组的索引作为自定义属性,方便后续查找对应完整内容
  3. 点击「查看更多」按钮时,先获取当前行绑定的索引,从数组中取出对应完整内容再填入模态框

修改后的完整JS代码

const form = document.querySelector("form");
const tbodyEl = document.querySelector("tbody");
const table = document.querySelector("table");
// 新增全局数组存储所有完整笔记内容
const noteList = [];
// 截断文本长度阈值,可自行调整
const TRUNCATE_LENGTH = 20;

function onAddNote(e) {
    e.preventDefault();
    const inputEl = document.getElementById("input");
    const inputVal = inputEl.value.trim();
    // 空内容不提交
    if(!inputVal) return;
    // 存入数组
    const noteId = noteList.length;
    noteList.push(inputVal);
    // 生成截断后的展示文本
    const showText = inputVal.length > TRUNCATE_LENGTH ? 
        inputVal.slice(0, TRUNCATE_LENGTH) + '...' : inputVal;
    // 渲染行,绑定noteId
    tbodyEl.innerHTML += `<tr data-note-id="${noteId}"><td>${showText}</td><td><button class="modalButton">View More</button><button class="deleteBtn">Delete Note</button></td></tr>`;
    // 清空输入框
    inputEl.value = '';
}

function onButtons(e) {
    if (e.target.classList.contains("deleteBtn")) {
        // 删除行
        const btn = e.target;
        const tr = btn.closest("tr");
        // 删除数组里对应的内容
        const noteId = +tr.dataset.noteId;
        noteList.splice(noteId, 1);
        tr.remove();
        return;
    }
    if (e.target.classList.contains("modalButton")) {
        const btn = e.target;
        const tr = btn.closest("tr");
        // 拿到对应id,取完整内容
        const noteId = +tr.dataset.noteId;
        const fullContent = noteList[noteId];
        // 生成模态框
        const modal = document.createElement('div')
        modal.classList.add('modal')
        const child = document.createElement('p')
        child.classList.add('child')
        // 填入对应完整内容
        child.innerHTML = fullContent;
        modal.appendChild(child)
        document.body.appendChild(modal)
        // 关闭按钮
        const modalBtn = document.createElement('button')
        modalBtn.innerText = "Close Note";
        modalBtn.classList.add('modalBtn')
        modal.appendChild(modalBtn)
        modalBtn.addEventListener('click', function () {
            document.body.removeChild(modal)
        })
        return;
    }
}

table.addEventListener("click", onButtons);
form.addEventListener("submit", onAddNote);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:27:01