为了账号安全,请及时绑定邮箱和手机立即绑定

带有 id 'notes' 的 div 不会在 javascript 代码中显示默认注释

带有 id 'notes' 的 div 不会在 javascript 代码中显示默认注释

芜湖不芜 2021-11-25 16:12:08
默认文本应该显示在带有 id 'notes' 的 div 中。包含用于显示注释的按钮的 Javascript 代码。有条件显示更新的注释和默认文本。给出了在更新之前应该显示的默认文本部分。但是,不显示默认文本。我没有发现任何错误。怎么做?<hr><h1>Your Notes:</h1><hr><!-- container-fluid use up all the available spaces --><div id="notes" class="row container-fluid"></div>function show_notes() {    let notes = localStorage.getItem("notes");    if (notes == null) {       notesObj = [];    }    else {        notesObj = JSON.parse(notes);    }    let html = "";    notesObj.forEach(function (element, index) {        //using backtick        html += `             <div class="noteCard my-2 mx-2 card" style="width: 18rem;">                    <div class="card-body">                        <h5 class="card-title">Note ${index + 1}</h5>                        <p class="card-text">${element}</p>                        <button href="#" class="btn btn-primary">Delete Note</button>                    </div>                </div>`;                  });               let notes_element = document.getElementById("notes");            if (notesObj.length != 0) {                notes_element.innerHTML = html;                //console.log("Add notes success!")            }            else {//default note                notes_element.innerHTML = `No note added. Use "Add Note" button to add a note.`;                //console.log('Notes not added!');            }        }
查看完整描述

2 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

如果notesObj被初始化为一个空数组,您forEach()将不会执行并添加默认的笔记 HTML。


const test = [];


test.forEach(() => console.log("won't log"));


查看完整回答
反对 回复 2021-11-25
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

非常感谢您的意见和解决方案。其实,我错了。函数 show_notes() 将在 .addEventListener 之前/之外和 .addEventListener 函数之内/结束时调用。


查看完整回答
反对 回复 2021-11-25
  • 2 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信