函数在卸载事件中工作,但在单击事件中不工作

Function working in an unload event but not in a click event

本文关键字:工作 事件 单击 函数 卸载      更新时间:2023-09-26

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

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>

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

查看您的代码,您定义了一个可变位置,并尝试使用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");
}