2

我有一个分为 5 个步骤的表格。目前,如果您在步骤 2-4 中刷新/退出/关闭等,它会通过 window.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.';
            }
        }

现在,如果复选框“A”被选中并且复选框“B”未被选中,我需要在 step0(第一步)上添加相同或相似类型的行为。这可行,但不能与另一个 .onbeforeunload 函数结合使用

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

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

4

1 回答 1

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),这只是一种更容易维护的方式。

Also you may want to add an additional check to the first if, ensure you're on that step, like this:

if ($('#step0').is(':visible') && $("#A").is(":checked") && !$("#B").is(":checked") ) {
于 2010-08-03T15:57:42.557 回答