功能在卸载事件中工作但不在单击事件中工作

时间:2014-11-07 16:53:26

标签: javascript jquery

我有一个注销功能,在两个不同的事件中调用。一个是卸载事件,另一个是点击事件。如果我卸载或刷新页面,则调用该函数并注销用户。但是,当我单击注销按钮时,该函数不会被调用。任何人都可以解释原因吗?

JS

var loc = "../pages/logged_out.php";
    function logout(location){
        $.post("../php/logout.php", {}, function(response){
            if(response.success == "1"){
                location.replace(location);
            }
        }, "json");
    }

    $("#logout").on("click", function(){
        logout(loc);
    })

    $(window).unload(function(){
        logout(loc);
    })

HTML

<button class="button" name="logout" id="logout">Logout</button>

编辑:我没有提到的一件事是,如果我将该函数设为匿名函数并且不尝试将该位置作为参数传递,则该脚本可以正常工作。

1 个答案:

答案 0 :(得分:0)

查看代码,您定义了一个变量位置并尝试使用location.replace

function logout(location){   <-- variable location
    $.post("../php/logout.php", {}, function (response){
        if(response.success == "1"){
            location.replace(location);   <-- trying to use replace on itself
        }
    }, "json");
}

location重命名为其他变量。浏览器毫无疑问您实际上是指window.location.replace()

function logout (redirectLocation) {   
    $.post("../php/logout.php", {}, function(response){
        if(response.success == "1"){
            window.location.replace(redirectLocation);   
        }
    }, "json");
}