vb.net 在 head 中定义的 JS 函数没有在 onLoad 中定义

vb.net JS function defined in head is not defined at onLoad

我有一个 vb.net 应用程序,在应用程序中,有提交报告的功能。

当用户回答了报告中的所有问题后,他们单击 'Submit' 按钮,并显示一个页面,其中显示一个要求他们输入密码的表单 - 一旦他们输入了密码(两次 'Password' 字段和 'Confirm Password' 字段),他们单击 'Continue' 按钮,然后转到显示 'Report Submitted' 消息和报告案例编号的页面他们提交了。至此,报告提交,信息记录在数据库中。

用户可以使用他们获得的案例编号和他们创建的密码重新登录系统,检查他们的雇主添加到他们报告中的任何反馈。

但是,如果用户填写报告并单击 'Submit' 按钮,如果他们单击浏览器 'Back' 按钮,或以其他方式返回页面,则存在一个问题当他们查看 'Enter Password' 页面时,他们将返回到他们填写报告的页面,并且他们之前输入的所有值仍显示在那里。

如果他们再次单击“提交”按钮(可能他们更改了之前输入的一些数据,也可能没有),则会生成第二份报告并将信息第二次记录在数据库中 - 因此这可能会导致重复记录。

我想尝试阻止用户在提交报告的这两个步骤中返回页面。

我遇到了关于 SO 的 this 答案,并尝试在我的项目中实现它。

但是,当我现在单击 'Submit' 提交完成的报告时,我的浏览器控制台会显示一条错误消息:

Uncaught ReferenceError: changeHashOnLoad is not defined at onload (passwordconfirm:118)

我在 passwordconfirm.aspx 中添加了函数和函数调用:

<head runat="server">
    ...
    <script>
        $(document).ready(function () {
            ...
            function changeHashOnLoad() {
                console.log("changeHashOnLoad() called ");
                window.location.href += "#";
                setTimeout("changeHashAgain()", "50");
            }

            function changeHashAgain() {
                window.location.href += "1";
            }

            var storedHash = window.location.hash;
            window.setInterval(function() {
                if (window.location.hash != storedHash) {
                    window.location.hash = storedHash;
                }
            }, 50);
            ...
        });
    </script>
</head>
<body onload="changeHashOnLoad(); ">
    ...
</body>

但我不确定为什么我在提交报告时收到 Uncaught ReferenceError 说明 changeHashOnLoad is not defined,并且提交确认页面已加载...

是否因为HTML标签的onload属性在HTML标签的<script></script>标签内的代码之前运行 ] <head></head>节?如果是这样,我如何确保 changeHashOnLoad() 函数在页面加载时已经定义 - 我应该在哪里定义该函数?

或者,如果不是,我做错了什么?

您正在 document.ready 回调函数中声明您的函数。这意味着您的哈希函数将在本地范围内,并且仅存在于该函数范围内。而是执行以下操作:

function changeHashOnLoad() {
  console.log("changeHashOnLoad() called ");
  window.location.href += "#";
  setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
  window.location.href += "1";
}

$(document).ready(function () {
  var storedHash = window.location.hash;
  window.setInterval(function () {
    if (window.location.hash != storedHash) {
      window.location.hash = storedHash;
    }
  }, 50);
});