首页 > 解决方案 > 每次点击都会增加数字

问题描述

我希望我的程序以数字方式排列注释,例如注释 1,再次单击应该是注释 2,依此类推,我将不胜感激您的解决方案。如果您想查看整个代码:https ://jsfiddle.net/Iamtsquare07/gw016q7s/3/

//Selecting document elements
            const noteArea = document.querySelector('#note');
            const noteBtn = document.querySelector('#noteSaveBtn');
            const noteRow = document.querySelector('.row');
            const columnNo = document.querySelector('.column');

            const noteApp = () => {        
                const noteText = noteArea.value;//getting the value from the note
                const noteFile = document.createElement('div');
                noteFile.id = 'filebody';
                noteFile.classList.add('column');
                const h2Inner = 'Note';
                noteFile.innerHTML = `<h2>${h2Inner}</h2><p>${noteText}</p>`;//I need to figure out how to add a number to the Note, to make it Note 1, Note 2...

                noteRow.appendChild(noteFile);
                noteArea.focus()

                noteArea.value = '';

                
            }

            noteBtn.addEventListener('click', noteApp);
<div id="noteHeader">
        <h1 id="noteH1">NO<span id="noteSpan">TED</span></h1>
        <h4 id="noteH4">Add a note</h4>
        <div>
            <div id="noteBox">
                <textarea id="note" placeholder="Start writing" wrap="physical" cols="100" rows="10"></textarea><br>
                <input id="noteSaveBtn" type="button" value="Save">
            </div>
            <br>
              </div>
              <div class="row">
                </div>
              </div>

标签: javascript

解决方案


您可以创建一个变量index并将其附加为${h2Inner + index},然后递增计数器。

//Selecting document elements
const noteArea = document.querySelector('#note');
const noteBtn = document.querySelector('#noteSaveBtn');
const noteRow = document.querySelector('.row');
const columnNo = document.querySelector('.column');

let index = 1;

const noteApp = () => {
  const noteText = noteArea.value; //getting the value from the note
  const noteFile = document.createElement('div');
  noteFile.id = 'filebody';
  noteFile.classList.add('column');
  const h2Inner = 'Note';
  noteFile.innerHTML = `<h2>${h2Inner + index}</h2><p>${noteText}</p>`; //I need to figure out how to add a number to the Note, to make it Note 1, Note 2...
  index++;
  noteRow.appendChild(noteFile);
  noteArea.focus()

  noteArea.value = '';


}

noteBtn.addEventListener('click', noteApp);
<div id="noteHeader">
  <h1 id="noteH1">NO<span id="noteSpan">TED</span></h1>
  <h4 id="noteH4">Add a note</h4>
  <div>
    <div id="noteBox">
      <textarea id="note" placeholder="Start writing" wrap="physical" cols="100" rows="10"></textarea><br>
      <input id="noteSaveBtn" type="button" value="Save">
    </div>
    <br>
  </div>
  <div class="row">
  </div>
</div>


推荐阅读