首页 > 解决方案 > Can't call function inside of jQuery plugin for a facebook login event

问题描述

I am trying to create a jQuery plugin which will ask for appID and create the facebook login option for the user.

My code is :

; (function($){
$.fn.fbLogin = function(options){
    var defaults = {
        appId: ''
    };

    var opt = $.extend(defaults, options);
    var fbRoot = "<div id='fb-root'></div>";
    var fbSdkLoad = "<script async defer crossorigin='anonymous' src='https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.3&appId=" + opt.appId + "&autoLogAppEvents=1'></script>";

    var fbLoginButton = `<div
        class="fb-login-button"
        data-width=""
        data-size="large"
        data-button-type="login_with"
        data-auto-logout-link="false"
        data-use-continue-as="true"
        data-scope="email"
        data-onlogin="loginFB();"
    />`;

    $("body").append(fbRoot);
    $("body").append(fbSdkLoad);
    $("body").append(fbLoginButton);

    function loginFB(){
        console.log("yes");
    }
}
})(jQuery);

when I load this plugin in my index.html file then Login with Facebook button is loaded. When I click it, a popup appears and then I got the following error in my dev console.

Uncaught ReferenceError: loginFB is not defined

When I add the loginFB function in index.html in a script, it works, which makes sense as login button is there in body scope, and can call the function.

But I want to have a function which will do some work after login which needs to be stayed inside the plugin function.

Can anyone suggest me any better approach for this ?

标签: jqueryjquery-plugins

解决方案


推荐阅读