Bootstrap 5表单验证通过后执行webShare()函数的实现求助
解决方案
你只需要在表单验证通过的分支里,阻止默认提交行为(避免页面刷新)并调用webShare()函数即可,修改后的代码如下:
function onLoad() { const forms = document.querySelectorAll('.needs-validation') Array.from(forms).forEach(form => { form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } else { // 验证成功:阻止默认提交,执行webShare函数 event.preventDefault() webShare() } form.classList.add('was-validated') }, false) }) if (navigator.share === undefined) { setShareButtonsEnabled(false); if (window.location.protocol === 'http:') { // navigator.share() is only available in secure contexts. window.location.replace(window.location.href.replace(/^http:/, 'https:')); } else { logError('Error: You need to use a browser that supports this draft ' + 'proposal.'); } } } window.addEventListener('load', onLoad);
修改说明:
- 新增
else分支,当form.checkValidity()返回true(表单验证通过)时,先调用event.preventDefault()拦截表单默认的提交刷新行为,然后执行你的webShare()函数。 - 原有的
form.classList.add('was-validated')保留,确保Bootstrap的验证状态样式正常生效。 - 请确保
webShare()函数已在全局作用域中定义,能被该事件监听器正常访问调用。
内容的提问来源于stack exchange,提问作者Psycho0verload
相关产品推荐
相关产品推荐

