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

http://img.mukewang.com/619f457b0001e64213530608.jpg

默认文本应该显示在带有 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!');

            }

        }


芜湖不芜
浏览 139回答 2
2回答

明月笑刀无情

如果notesObj被初始化为一个空数组,您forEach()将不会执行并添加默认的笔记 HTML。const test = [];test.forEach(() => console.log("won't log"));

眼眸繁星

非常感谢您的意见和解决方案。其实,我错了。函数 show_notes() 将在 .addEventListener 之前/之外和 .addEventListener 函数之内/结束时调用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript