preventDefault() 被 window.location 否决

preventDefault() overruled by window.location

我的网站上有流程,其中包含几个步骤。要导航,我有 "previous" 和 "next" 按钮。这些按钮是具有 href 属性的 <a> 元素(用于访问上一步和下一步)。

下一步按钮可以作为下一步的入口,也可以在继续之前验证当前步骤中的某些字段。

所以这就是单击下一步按钮时发生的情况:

  1. href 值保存在变量中 $url
  2. preventDefault() 阻止 link 打开 URL。
  3. 已完成一些验证检查。
  4. 如果他们 return "true",$url 将加载到 window.location。

对于某些步骤,我需要使用确认框对用户进行另一次检查。但是问题来了:

问题:

confirm() returns "false"时,用户不应该进入下一页。但是现在函数1的window.location"overrules"函数2的preventDefault().

1.默认下一个按钮功能:

$('#next_link').click(function(e) {
    var url = $(this).attr('href');
    e.preventDefault();             
    if(wiz_validate_required() && wiz_is_step_done()) {
        window.location = url;  
    } 
}); 

2。确认框功能:

$('.dimensions-check').click(function(e) {
    if(confirm('Have you specified the dimensions in millimeters?') == false) {
        e.preventDefault();
    }
});

在哪里调用维度检查?

e.preventDefault() 只取消提交表单按钮的默认动作。不管 e.preventDefault windows.location 总是重定向你。

$('#next_link').click(function(e) {
    var url = $(this).attr('href');
    e.preventDefault();             
    if(wiz_validate_required() && wiz_is_step_done()) {
        //If dimension isnot prompt{
          //windows.location
        //}else call dimension prompt
            
    } 
});

你可以这样放置 windows.location:

$('.dimensions-check').click(function(e) {
    if(confirm('Have you specified the dimensions in millimeters?') == true) {
        window.location = url;
    }
});

我会做那样的事情。如果您对代码有任何疑问,请提问!

fiddle

    // These can be changed for each step if you want or not a confirmation 
   var needs_confirm = true;
   var cb_message = 'Have you specified the dimensions in millimeters?';

   $('#next_link').click(function(e) {

     var url = $(this).attr('href');
     e.preventDefault();

     if (needs_confirm === true) {
       if (confirm_box(cb_message) === true) {
         redirect_window(url);
       }
     } else {
       redirect_window(url);
     }

   });


   function confirm_box(cb_message) {
     if (confirm(cb_message) === true) {
       return true;
     } else {
       return false;
     }
   }

   function redirect_window(url) {
     if (wiz_validate_required() && wiz_is_step_done()) {
       window.location = url;
     }
   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="next_link"><a href="#">link</a>
</div>