You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:31:01