id为';附注';不';t在javascript代码中显示默认注释。默认情况下如何显示?
id为';附注';不';t在javascript代码中显示默认注释。默认情况下如何显示?,javascript,html,Javascript,Html,默认文本应显示在具有id的div内 “注释” 包含用于显示注释的按钮的Javascript代码 有条件显示更新的注释和默认文本 未给出更新前应显示的默认文本部分 但是,不显示默认文本。我没有发现任何错误。怎么做 <hr> <h1>Your Notes:</h1> <hr> <!-- container-fluid use up all the available spaces --> <div id="notes" class="
<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!');
}
}
你的笔记:
函数show_notes(){
让notes=localStorage.getItem(“notes”);
if(notes==null){
注sobj=[];
}
否则{
notesObj=JSON.parse(notes);
}
设html=“”;
notesObj.forEach(函数(元素、索引){
//使用backtick
html+=`
注${index+1}
${element}
删除注释
`;
});
让notes_element=document.getElementById(“notes”);
如果(注:长度!=0){
notes_element.innerHTML=html;
//log(“添加注释成功!”)
}
else{//默认注释
notes_element.innerHTML=`未添加注释。使用“添加注释”按钮添加注释。`;
//log('未添加注释!');
}
}
如果
notesObj
被初始化为空数组,则您的forEach()
将不会执行并添加默认的注释HTML
const test=[];
test.forEach(()=>console.log(“不会记录”)代码>非常感谢您的观点和解决方案。事实上,我错了。函数show_notes()是在.addEventListener之前/之外和.addEventListener函数的内部/末尾调用的 似乎默认注释需要在localStorage
中。您检查过了吗?实际上,localStorage只存储添加的注释,而不是默认注释。默认文本在背景标记中。这会产生问题吗?我已经测试了你的代码,只要你声明notesObj
并调用你的show\u notes
函数,它就会工作。