2012-06-03 61 views
1

我有下面的JavaScript檢查是否卸載

編輯之前保存的更改:包括分配用於cahngesSaved

var changesSaved = true; 

    $(document).ready(function() { 

     $(".applyChanges").click(function (e) { 
      e.preventDefault(); 
      var id = (this).id; 
      var dayofweek = document.getElementById("dayofweek" + id).value; 
      var hour = document.getElementById("hour" + id).value; 
      var duration = document.getElementById("duration" + id).value; 
      $.ajax({ 
       url: '@Url.Action("ApplyChanges")', 
       type: 'POST', 
       data: { 
        id: id, 
        dayofweek: dayofweek, 
        hour: hour, 
        duration: duration 
       }, 
       success: function (data) { 
        $('#Calendar').fullCalendar('refetchEvents') 
        $('#Calendar2').fullCalendar('refetchEvents') 
        changesSaved = false; 
       } 
      }); 
     }); 
    }); 

window.onbeforeunload = function() { 
    if (changesSaved == true) { 
     return true; 
    } else { 
     return ("You havent saved your changes. Are you sure you want to leave the page?") 
    } 
} 

但該消息被無論使用什麼changesSaved設置過的提示。

什麼其實我真正得到如下:

enter image description here

,或者如果changesSaved設置爲false,它說假的來代替。

我可以不這樣做嗎?

+0

你在哪裏設置'changesSaved'? –

+0

添加'console.log(changesSaved)'並查看函數內部的值。 –

回答

2
<body onbeforeunload="return bye()"> 

function bye(){ 
    if(changesSaved) { 
     return "You havent saved your changes." 
    } 
} 

這就是我該怎麼做的。

或純JavaScript:

window.onbeforeunload = function() { 
    if (changesSaved) { 
     return "You haven't saved your changes."; 
    } 
}; 
+1

有趣的是,我只是希望它彈出一個對話框,用「未定義」,但似乎在鉻工作 – Esailija

+0

@Esailija - 簡化代碼後,它現在不那麼奇特了。 (只是開玩笑';)') –

0
window.onbeforeunload = function() { 
    var changesSaved = confirm("You havent saved your changes. Are you sure you want to leave the page?"); 
    if (changesSaved) { 
     return true; 
    } else { 
     return false; 
    } 
+0

當你點擊'取消',頁面仍然關閉。 –

+0

@Derek現在檢查 – Yehonatan

+0

關鍵是你不需要'確認'那裏。 –