0

我目前有一个格式与此类似的网页,带有侧边栏和 iframe,其来源指向我网站上的其他页面。

在此处输入图像描述

我有以下代码可以为用户提供一个确认框,以确认他们是否希望离开该页面:

window.onbeforeunload = function(e) {
    return 'All unsaved data will be lost.';
};

在 iframe 中,我有各种 HTML 元素,例如文本字段、输入框、按钮等。我不希望用户获得该onbeforeunload功能,除非他们首先单击这些输入元素之一。

当然,我可以进入并编写每个文本字段、按钮等的代码,通过创建一个变量shouldPopuponclick例如未来更多的变化,我可能不得不再次进入并修改每个元素。shouldPopupTRUEonbeforeunload

获得相同结果的更好方法是什么?非常感谢有关如何简化代码的任何输入!:)

更新:

有关我的 iframe 的更多信息。我将 jQuery 库用于一些基本功能(没什么花哨的)。其中有相当多的 PHP,以及一些数据库请求,但没有什么特别之处。希望这些信息对希望提出任何建议的人有所帮助

4

2 回答 2

1

If you don't want to change too much of your code, I think toggeling a flag is OK. The following is a simple, pragmatic approach.

Example form:

<input type="text" class="form" ...>
<input type="text" class="form" ...>
<select class="form" ...>
   <option value=""></option>
   ...
</select>

Monitor changes in both iFrames:

(function(){
  // This can be optimized to check against saved values on blur
  $("body").on("change", ".form", function(evt){
    window.top.$(window.top).trigger("change-form"); // trigger custom event in parent page
  });
}());

Parent page:

(function(){
  var dirty = false
  $(window).on("change-form", function(){
    dirty = true;
  });

  window.onbeforeunload = function(e) {
    // Notify user only if forms are dirty
    return dirty ? 'All unsaved data will be lost.' : undefined;
  };
}());

This code is braindump, it's untested.

Note: If your pages are served from different domains than the parent page you'll run into cross site scripting issues. In that case you're not able to access the parent page's Javascript. Then you have to use postMessage() to send messages to your parent page's domain.


I'd suggest you to take a look at Backbone.js:

Edit 1:

Backbone can help you managing the state of your form. In Backbone a Model will represent your form data. A View - representing your form (form's inputs) - is bound to that Model. It will monitor your form fields and set() attributes on the model. A Backbone Model has its own state, you can check if the form has chnaged using e.g. the changed() method. Separating Model and View in your application is always a good idea, it helps separating the responsibilities.

I just wanted to give you another idea.

Edit 2:

Fixed the code that triggers an event in the top window. I was not sure if $(window.top) works. It does not work. I'm not sure why. I've tested it and this code is correct:

window.top.$(window.top). ...

I've updated the above code.

于 2013-01-21T22:18:33.590 回答
1

似乎您正在寻找(基本上)一个脏标志(就像这里的 SO 使用)。本质上,因为这是对设计的补充,所以将脚本与 UI 分开,只使用某种选择器来获取所有可能被更改的元素并绑定一个简单地监视和更改脏标志的事件。

为简洁起见,这里有一个 jQuery 版本:

var isDirty = false;
$(':input').on('change', function(e){
  isDirty = true;
});
$(window).on('beforeunload',function(e){
  if (isDirty){
    // Alert th euser there's unfinished changes
  }
});

非常简单,并且将脚本分开。此外,如果这些是您的子窗口,您可以引用window.parent并将标志传递给主视图(如果您选择了)。

于 2013-01-21T22:02:07.647 回答