首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试在窗体向导的第一步中重写onbeforeunload

尝试在窗体向导的第一步中重写onbeforeunload
EN

Stack Overflow用户
提问于 2010-06-18 10:41:05
回答 1查看 446关注 0票数 1

这是一个有5个步骤的表单向导,我不希望用户在任何步骤2-4中点击并丢失表单数据。我已经为提交函数添加了一个标志,并且需要为第一步添加这个标志。如果他们偶然到达那里并试图离开,我不希望弹出确认对话框。

代码语言:javascript
复制
<script type="text/javascript">
    $(document).ready(function(){
      var action_is_post = false;
    $("form").submit(function () {
    action_is_post = true;
 });

//this is the trouble spot. on the first step the "navigation" of the form has a class 
//of current (on step one = current)
$(this).ready(function () {
if ($("#stepDesc0").is(".current")) {
action_is_post = true;    
}
);   

window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'Using the browsers back, refresh or close button will cause you to lose all
form data. Please use the Next and Back buttons on the form.';
}
});
</script>
EN

回答 1

Stack Overflow用户

发布于 2010-06-18 11:17:58

变量action_is_post被声明为$(document).ready()的局部变量,当它到达函数confirmExit()时,它在不同的作用域中。因此,它是未定义的,因此在条件语句中为false。尝试在$(document).ready()外部添加声明,如下所示:

代码语言:javascript
复制
var action_is_post = false;
$(document).ready(function(){
    $("form").submit(function () {
    action_is_post = true;
});

这使变量成为全局变量,并且它的行为应该符合您的期望。

编辑:我检查了你页面中的代码,它非常复杂,很难理解。我的建议是简单地对confirmExit()函数中的类再次运行比较检查,而不是检查action_is_post变量的值。

代码语言:javascript
复制
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (!$("#stepDesc0").hasClass(".current"))
      return 'Using the browsers back, refresh or close .....';
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3066918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档