且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止 HTML 页面刷新

更新时间:2023-12-01 22:54:10

由于您在技术上通过单击提交按钮来提交表单,因此会创建页面刷新.您需要使用 preventDefault 函数取消提交事件,该函数如果可以取消则取消该事件,而不会停止该事件的进一步传播."

Since you're technically submitting your form by clicking the submit button, then that creates the page refresh. You need to cancel the submit event with the preventDefault function, which "Cancels the event if it is cancelable, without stopping further propagation of the event."

在此处查看文档:https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

所以也许您可以尝试以下方法(直接来自文档):

So maybe you can try something along these lines (straight from the docs):

function stopDefAction(evt) {
    evt.preventDefault();
}

document.getElementById('my-checkbox').addEventListener('click', stopDefAction, false);

另一种选择是删除表单/输入元素并简单地使用按钮元素代替,这不会在点击时触发页面刷新.

Another option is to remove the form/input elements and simply use a button element instead, which doesn't trigger a page refresh on click.