页面点击按钮刷新

huangapple go评论136阅读模式
英文:

Page refresh on button click

问题

<!-- HTML -->
<div class="visible" id="render-body"></div>
<form id="edit-el" class="d-none">
  <textarea
    id="edit-body-el"
    cols="30"
    rows="15"
    class="form-control"
  ></textarea>
  <button id="edit-btn" class="m-2 button">
    Save
  </button>
</form>

// JavaScript
editBtn.addEventListener("click", function () {
  let myNotes = JSON.parse(localStorage.getItem("notes"));
  let savedIndex;
  for (let i = 0; i < myNotes.length; i++) {
    if (myNotes[i].name === noteObject.name) {
      myNotes.splice(i, 1);
      savedIndex = i;
    }
  }
  noteObject.body = editBodyEl.value;
  myNotes.push(noteObject);
  updateNotes(myNotes);
  bodyRenderEl.className = "visible";
  editEl.className = "d-none";
  renderNoteBody();
});
英文:
&lt;!-- HTML --&gt;
&lt;div class=&quot;visible&quot; id=&quot;render-body&quot;&gt;&lt;/div&gt;
            &lt;form id=&quot;edit-el&quot; class=&quot;d-none&quot;&gt;
              &lt;textarea
                id=&quot;edit-body-el&quot;
                cols=&quot;30&quot;
                rows=&quot;15&quot;
                class=&quot;form-control&quot;
              &gt;&lt;/textarea&gt;
              &lt;button id=&quot;edit-btn&quot; class=&quot;m-2 button&quot;&gt;
                Save
              &lt;/button&gt;
            &lt;/form&gt;

//JavaScript
editBtn.addEventListener(&quot;click&quot;, function () {
  let myNotes = JSON.parse(localStorage.getItem(&quot;notes&quot;));
  let savedIndex;
  for (let i = 0; i &lt; myNotes.length; i++) {
    if (myNotes[i].name === noteObject.name) {
      myNotes.splice(i, 1);
      savedIndex = i;
    }
  }
  noteObject.body = editBodyEl.value;
  myNotes.push(noteObject);
  updateNotes(myNotes);
  bodyRenderEl.className = &quot;visible&quot;;
  editEl.className = &quot;d-none&quot;;
  renderNoteBody();
});

I created edit button to edit current note. When I press on it it does functional part like updating array and saving it into local storage, but instead rendering updated note on webpage it refreshes it.

答案1

得分: 1

因为您正在使用一个表单,按钮将重新加载页面。为了防止这种情况,有两个选项:

不使用表单或使用以下代码:

editBtn.addEventListener("click", (event) => {
    event.preventDefault(); // 阻止按钮点击时的默认表单回调。
    saveNote();
});
英文:

Since you are using a form, the button will reload the page. To prevent this, there are 2 options:

Do not use form or use this code:

editBtn.addEventListener(&quot;click&quot;, (event) =&gt; {
        event.preventDefault(); // Prevent default form callback from button clicking.
        saveNote();
    });

huangapple
  • 本文由 发表于 2023年3月15日 18:18:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定