我在使用 G+ 登录我的网站时发现了这个问题。
我的网站上有工具栏(用 Javascript 呈现)和 G+ 登录按钮,所以我在工具栏文件中附加了 G+ Javascript API
[工具栏-notlogin.php]
<script>
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js?onload=render';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function render ()
{
var config = {
"callback": "loginCallback",
"clientid": "xxxxxxxxx.apps.googleusercontent.com",
"cookiepolicy": "single_host_origin",
"requestvisibleactions": "http://schemas.google.com/AddActivity",
"scope": "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email"
};
$('#googleCustomLoginBtn .buttonText').text('Login with Google');
gapi.signin.render ("gplusLoginBtn", config);
}
</script>
当工具栏(使用 G+ JS API)加载时,它会调用回调函数 render() 来呈现 G+ 登录按钮。它工作得很好,所以我的工具栏变成了登录状态(显示用户的个人资料)并且 G+ 登录按钮消失了(HTML 被替换)。
当用户注销时,工具栏将状态更改为未登录(再次替换 HTML),它会再次调用 render() 并且登录按钮起作用。
但问题是当我这次登录时,回调函数 ( loginCallback() ) 调用了两次。好像回调函数又绑定(bind)了。 (我尝试第二次不调用 render() 但登录按钮不起作用。)
有什么办法可以解决吗?谢谢。
最佳答案
有点新手,但我记得在某处读到过,在某些情况下,您可能会不小心多次调用该函数,因为您已将它绑定(bind)到多个元素。您是否尝试过在声明之前直接删除事件处理程序?
这样,如果已经有它的一个实例,它将在添加另一个实例之前被删除。
类似这样的东西
$('#randomID').unbind('submit').bind('submit');
关于javascript - G+登录按钮回调绑定(bind)两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972853/