【问题标题】:Page exit confirmation页面退出确认
【发布时间】:2014-07-15 17:40:20
【问题描述】:

我的 rails 应用程序存在一些问题。当用户输入数据然后尝试通过任何方式(提交除外)离开页面时,我希望它提示他们确认离开页面。这是我到目前为止的代码,它在一定程度上有效。如果用户填写了一些数据然后点击“提交”,他们仍然会被提示确认离开页面。如果他们选择留在页面上,然后再次单击“提交”,它将按预期工作。

var clean;
var submitted = false;

$(function(){
  clean = $("form").serialize();
});

window.onbeforeunload = function(){
  $("form").submit(function() {
    submitted = true;
  });
  var dirty = $("form").serialize();
  if (dirty != clean && !submitted) {
    return "You have unsaved data that will be lost if you leave the page.";
  }
};

我还希望在用户尝试点击页面上的某个链接(不仅仅是关闭它等)时出现提示。我正在使用 jquery-turbolinks 但它似乎仍然没有选择这些事件。

对于这些问题的任何帮助,我们将不胜感激!

【问题讨论】:

    标签: javascript ruby-on-rails turbolinks


    【解决方案1】:

    这是一个可能的解决方案:

    <script type="text/javascript">
    $(document).ready(function() {  
    
      var isEdit  = false;  
    
      $('input').change(function() {  
        isEdit = true;  
      });  
    
      function checkIsEdit() {  
        if(isEdit)  
          return "You have modified some content. Please save this form.";  
      }  
    
      window.onbeforeunload = checkIsEdit;  
      $(document).submit(function(){
        isEdit = false;
      });
    });  
    </script>
    

    (基于http://www.webstuffshare.com/2010/03/code-snippet-jquery-confirm-before-exit/)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 2014-04-23
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多