离开页面时提示用户

时间:2014-05-30 16:01:20

标签: javascript asp.net onbeforeunload

在我的页面上,我有一个名为cbOrderSpareCustomer的组合框。 默认情况下,所选索引设置为0。

当用户更改它时,我认为该页面包含数据,当用户决定离开页面时,我想提示他让他知道数据将会丢失。

我看过很多关于此的帖子,但我对javascript很新,所以我可以使用一些帮助。

我明白我必须使用:

<script>
window.onbeforeunload= function() { return "Custom message here"; };
</script>

但是如何让它与组合框一起使用?

喜欢if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.

我还想阻止它在每次回发时显示提示。

我想看一个例子。

5 个答案:

答案 0 :(得分:2)

你在客户端获得下拉列表,并检查索引,你的代码可能是:

<script>
window.onbeforeunload= function() 
    { 
        if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0)
        {
            return "Custom message here"; 
        }
        else
        {
            return true;
        }
    };
</script>

答案 1 :(得分:1)

我想......

window.onbeforeunload = function(e) {
    if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) {
        if (!confirm('Are you sure')) {
            return false;
        }
    }
}

答案 2 :(得分:1)

按照以下步骤进行此操作

  1. 使用以下代码将onchange属性添加到服务端的组合框:   <select id="cbOrderSpareCustomer" onchange="setDirty()">
  2. 将您的javascript定义如下

    var isDirty = true;
    function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }

答案 3 :(得分:0)

如果你正在使用JQuery

<script type="text/javascript">
    $(window).bind('beforeunload', function () {
        if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) {
            return 'Your data will be lost.';
        }
    });
</script>

您不希望其他方式返回true或仍然会提示(至少IE提示)

答案 4 :(得分:-1)

我的解决方案:

<script type="text/javascript"
function setDirty() {
            window.onbeforeunload = function () {
                return 'The data will be lost if you leave this page!'
            }
        }
</script>

使用属性onCange =&#34; setDirty()&#34;添加到下拉列表中。

感谢大家的帮助!

相关问题