javascript – 即使我刚刚使用它也是未定义的

前端之家收集整理的这篇文章主要介绍了javascript – 即使我刚刚使用它也是未定义的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试添加一个Facebook Like按钮到我创建的小部件.我用来添加Facebook的按钮到我的页面代码如下:

widget.html

<body>
<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId  : '263071593731910',status : false,// check login status
            cookie : true,// enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML
        });
    };
    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
</script>
<div id="fb-button"></div>
<script type="text/javascript" src="widget.js"></script>

widget.js

$(function(){
var fb = $(document.createElement("fb:like"));
fb.attr({
    href: data.facebook,send: false,layout: 'button_count',width: 70,'show_faces': false
});
$("#fb-button").empty().append(fb);
FB.XFBML.parse($("#fb-button").get(0));
FB.Event.subscribe('edge.create',changeView);
});

*在JavaScript中也存在changeView函数.

当我运行代码时,我收到一个错误:未捕获的ReferenceError:即使创建了按钮,FB也没有定义.错误指向包含FB.XFBML.parse代码的行.在JavaScript中有什么需要做的不同吗?

解决方法

从window.fbAsyncInit开始的那个大脚本块的全部点是,Facebook SDK被异步加载.

即使您已经在一个jQuery文档中调用了FB来调用回调,这还不足以确保在执行代码时加载SDK.

幸运的是,window.fbAsyncInit完全符合这个目的:它将不会运行,直到SDK加载.

Facebook’s docs

The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example,this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.

猜你在找的JavaScript相关文章