user1921267
user1921267

Reputation: 79

jQuery.each does not work in window.onbeforeunload function

I have this code:

HTML:

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

JS:

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

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

When I try to close a chrome tab, the confirm popup does not appear. Why?

Upvotes: 0

Views: 91

Answers (2)

Rajeev
Rajeev

Reputation: 312

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

Upvotes: 1

Barmar
Barmar

Reputation: 780889

You're just returning from the iteration function, not from the beforeunload handler. The only thing jQuery does with the return value of the function is test whether it's false, and stop the iteration. 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;
};

Upvotes: 4

Related Questions