你怎么禁用退出弹出窗口?

时间:2014-04-16 22:32:24

标签: javascript

我正在使用此脚本,当他们尝试退出页面时会弹出警告。但问题是当我点击一个重定向到另一个页面的按钮时它仍会弹出。我想在点击按钮时禁用它。我怎么能这样做?

<script language="javascript">
(function() {
    var __redirect_to = 'http://google.ca';//put redirect URL here

    var _tags = ['button', 'input', 'a'], _els, _i, _i2;
    for(_i in _tags) {
        _els = document.getElementsByTagName(_tags[_i]);
        for(_i2 in _els) {
            if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit') || _els[_i2].target == '_blank') continue;
            _els[_i2].onclick = function() {window.onbeforeunload = function(){};}
        }
   }

    window.onbeforeunload = function() {
        setTimeout(function() {
            window.onbeforeunload = function() {};
            setTimeout(function() {
                document.location.href = __redirect_to;
            }, 500);
        },5);
        return 'Do you really want to leave? Stay to go somewhere else.';
    }
})();
</script>

2 个答案:

答案 0 :(得分:0)

删除此行:

_els[_i2].onclick = function() {window.onbeforeunload = function(){};}

和这些:

window.onbeforeunload = function() {
    setTimeout(function() {
        window.onbeforeunload = function() {};
        setTimeout(function() {
            document.location.href = __redirect_to;
        }, 500);
    },5);
    return 'Do you really want to leave? Stay to go somewhere else.';
}

答案 1 :(得分:0)

如果你分析它,你可以看到,有一个标签名称数组

var _tags = ['button', 'input', 'a'], _els, _i, _i2;

并且对于其中的每个元素,它都应用onlick事件

for(_i in _tags) {
    _els = document.getElementsByTagName(_tags[_i]);
    for(_i2 in _els) {
        if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit') || _els[_i2].target == '_blank') continue;
        _els[_i2].onclick = function() {window.onbeforeunload = function(){};}
    }
}

所以只需删除数组的标签名称“按钮”

var _tags = ['input', 'a'], _els, _i, _i2;