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

点击保存答案按钮后页面自动回到顶部问题排查

解决点击保存按钮后页面自动回到顶部的问题

你遇到的问题核心是e.preventDefault()没阻止住页面默认的跳转/刷新行为,导致页面回到顶部,以下是几个针对性的解决思路:

1. 修改按钮类型

如果你的#SaveAnswerButton是<button>标签,它的默认类型是submit,即使绑定了click事件,点击时仍会触发表单的提交行为(页面刷新回到顶部)。直接修改按钮类型为button即可:

<button id="SaveAnswerButton" type="button">保存答案</button>

2. 改用表单submit事件监听

放弃监听按钮click,转而监听表单的submit事件,能更直接地阻止表单默认提交:

$('#answerform').submit(function(e) {
    e.preventDefault(); // 阻止表单默认提交行为
    let formDta = $(this).serialize();
    
    $.ajax({
        url: '@Url.Action("SaveAnswer", "AnswerPage")',
        data: formDta + '&currentAction=' + 0 + '&guid=' + "@guid",
        type: 'POST',
        datatype: "json",
        success: function (data) {
            if (typeof data.expired != "undefined") {
                window.location = data.expired;
            }
            else {
                var urllink = '@Url.Action("AnswerPage", "AnswerPage")?action1=' + data.action1 + '&guid=' + "@guid";

                if (data.status === 0) {
                    Swal.fire({ title: 'Saved Successfully', type: 'success', showCancelButton: false, showConfirmButton: false });
                    window.location.replace(urllink);
                }
            }
        }
    });
});

此时按钮可保留type="submit",点击按钮会触发表单的submit事件。

3. 增强事件阻止逻辑

如果坚持使用按钮click事件,在现有代码中添加e.stopPropagation(),防止事件冒泡触发表单提交:

$('#SaveAnswerButton').click(function (e) {
    e.preventDefault();
    e.stopPropagation(); // 阻止事件冒泡至表单
    let obj = {};
    let formDta = $("#answerform").serialize();
              
    $.ajax({
        // 原有ajax代码保持不变
    });
});

额外检查点

  • 若按钮是动态生成的,需用事件委托绑定事件:
$(document).on('click', '#SaveAnswerButton', function(e) {
    e.preventDefault();
    // 后续业务代码
});
  • 打开浏览器控制台检查是否有报错,若ajax请求失败,未处理的错误可能导致页面行为异常。

内容的提问来源于stack exchange,提问作者gudeThings

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:53:26