2017-03-02 26 views
0

我有一個窗體,底部有各種導航按鈕。如果用戶對錶單進行了更改,然後單擊除此之外的任何鏈接或按鈕,則應該給它們一個瀏覽器警報,警告他們有關未保存的更改。在IE中選擇事件目標元素

導航按鈕都具有數據屬性data-save-form,和腳本是目前如下:

var formChanged = false; 

$('form').on('change', 'input, textarea, select', function() { 
    formChanged = true; 
}); 

$(window).on('beforeunload', function (e) { 
    if (!$(e.target.activeElement).is('[data-save-form]') && formChanged) { 
     return "Changes you made may not be saved. You can save your progress by clicking the 'Save and Exit' button at the bottom of the page."; 
    } 
}); 

然而,IE的事件對象似乎並不具有target.activeElement財產。我怎樣才能找到這個元素,還是有更好的方法來處理這個問題?

這是一個使用jQuery 1.11.0的舊版網站,但我確定使用它不是必需的。

回答

0

我設法通過捕獲mousedown事件目標並使用它來使它工作,如果e.target.activeElement未定義。

var targetElement; 

$(window).on('mousedown', function (e) { 
    targetElement = e.target; 
}); 

$(window).on('beforeunload', function (e) { 
    var target = e.target.activeElement || targetElement; 
    if (!$(target).is('[data-save-form]') && formChanged) { 
     return "Changes you made may not be saved. You can save your progress by clicking the 'Save and Exit' button at the bottom of the page."; 
    } 
}); 

我在之前的另一個SO帖子中看到了類似這樣的解決方案,但無法使其工作。如果我找到它,我會鏈接它。