简体   繁体   English

jQuery.each在window.onbeforeunload函数中不起作用

[英]jQuery.each does not work in window.onbeforeunload function

I have this code: 我有以下代码:

HTML: HTML:

<div id="wrapper">
    <div>d</div>
    <div>s</div>
    <div>w</div>
</div>

JS: JS:

window.onbeforeunload = function(e) {
    $('#wrapper>div').each(function(k,v) {
        if($(this).text() == 's') {
            return 'aaaa';
        }
    });
}

http://jsfiddle.net/edhvkhg7/2/ http://jsfiddle.net/edhvkhg7/2/

When I try to close a chrome tab, the confirm popup does not appear. 当我尝试关闭Chrome浏览器标签时,不会出现确认弹出窗口。 Why? 为什么?

You're just returning from the iteration function, not from the beforeunload handler. 您只是从迭代函数中返回,而不是从beforeunload处理程序中返回。 The only thing jQuery does with the return value of the function is test whether it's false , and stop the iteration. jQuery对函数的返回值所做的唯一一件事就是测试它是否为false ,并停止迭代。 It doesn't get returned from the containing function. 它不会从包含的函数中返回。

window.onbeforeunload = function(e) {
    var return_val = null;
    $('#wrapper>div').each(function(k,v) {
        if($(this).text() == 's') {
            return_val = 'aaaa';
            return false; // End the loop
        }
    });
    return return_val;
};
window.onbeforeunload = function(e) {
    $('#wrapper>div').each(function(k,v) {
        if($(this).text() == 's') {
            $(this).text('aaaa');
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM