英文:
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();
});
英文:
<!-- 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();
});
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("click", (event) => {
event.preventDefault(); // Prevent default form callback from button clicking.
saveNote();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论