2010-08-03 68 views
2

我有一个表格分成5个步骤。目前,如果您在步骤2-4中刷新/退出/关闭等,它会通过window.onbeforeunload返回一条消息,在那里没有问题。如果条件满足,显示警报,几乎像onbeforeunload

window.onbeforeunload = function() { 
      if ($("#step1").is(":visible") || $("#step2").is(":visible") || $("#step3").is(":visible")) { 
       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.'; 
      } 
     } 

现在我需要添加的相同或类似类型的行为上step0(第一步骤),如果复选框“A”被选中,复选框“B”则不是。这个工程,但没有与另一个.onbeforeunload功能相结合

window.onbeforeunload = function() { 
      if ($("#A").is(":checked") && $("#B").is(":not(:checked)")) { 
       return 'Message here. Do you wish to continue?'; 
      } 
     } 

我怎样才能将这两个链接在一起?使用if,else语句似乎不起作用。

+0

这是否与你是如何加入他们吗?一目了然一个任务将覆盖另一个,但如果您使用jquery.bind(http://api.jquery.com/bind/),那么我认为它会正确处理添加多个事件处理程序...(作为评论因为我不确定是否可以作为答案)。 – Chris 2010-08-03 15:59:16

回答

3

你可以像这样的一个功能将它们组合起来:

window.onbeforeunload = function() { 
    if ($("#A").is(":checked") && !$("#B").is(":checked")) { 
     return 'Message here. Do you wish to continue?'; 
    } 
    if ($("#step1, #step2, #step3").filter(":visible").length) { 
     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.'; 
    } 
} 

我简化你的其他选择来获取所有的元素,.filter()只有:visible的人,看看是否有任何(.length> 0),这仅仅是一个易于维护的方式去实现它。

你也可能要额外的检查,添加到第一if,确保你在这一步,就像这样:

if ($('#step0').is(':visible') && $("#A").is(":checked") && !$("#B").is(":checked")) { 
+0

嘿尼克,这里是页面https://www.kinetick.com/purchase测试它没有按照需要工作。也许我不需要#step0的onbeforeunload?只有当我刷新时,它才会在下一次触发时触发。这应该是一个验证的事情?如果是这样,如果需要选择,我该如何避免陷入循环?如果“#A”只是一个警告,那么检查“#B”并不是绝对的。 – 2010-08-03 16:09:12

+0

@Dirty - 就你的情况而言,听起来你想要在第一个“下一步”按钮上进行A/B检查,这是否正确? – 2010-08-03 16:40:19

+0

是,由于某种原因,这是不工作... <脚本类型= “文/ JavaScript的”> \t \t $( “#step0Next”)。一个( '点击',函数(){ \t \t \t如果$(“#A”)。is(“:checked”)&& $(“#B”)。is(“:not(:checked)”)){ \t \t \t alert(“foo”); \t \t} \t}); \t – 2010-08-03 16:41:26