未捕获的引用错误:未定义 FB

我知道这个问题经常被问到,但我还没有找到解决方案。我用这个代码:

打开 html 标记

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">

在索引紧跟在开始标签之后,我输入了这个

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : 'MY_APP_ID',                        // App ID from the app dashboard
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page
    });

    // Additional initialization code such as adding Event Listeners goes here
  };

  // Load the SDK asynchronously
  (function(){
     // If we've already installed the SDK, we're done
     if (document.getElementById('facebook-jssdk')) {return;}

     // Get the first script element, which we'll use to find the parent node
     var firstScriptElement = document.getElementsByTagName('script')[0];

     // Create a new script element and set its id
     var facebookJS = document.createElement('script'); 
     facebookJS.id = 'facebook-jssdk';

     // Set the new script's source to the source of the Facebook JS SDK
     facebookJS.src = '//connect.facebook.net/it_IT/all.js';

     // Insert the Facebook JS SDK into the DOM
     firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
   }());
</script>

最后,按钮

<fb:like href="http://mydomain.it/" layout="button_count" action="like" show_faces="false" share="false"></fb:like>
<script>
FB.Event.subscribe('edge.create',
 function(href, widget) {
    alert('Ti piace ' + href);
});
</script>

类似的工作,但没有打开警报,我在控制台中收到此错误。

Uncaught ReferenceError: FB is not defined

任何解决方案?


答案 1

请参阅此主题:FB未在Facebook Login中定义

您正在尝试在按钮之后使用,但尚未定义:FB

<fb:like href="http://mydomain.it/" layout="button_count" action="like" show_faces="false" share="false"></fb:like>
<script>
FB.Event.subscribe(...
^--- FB isn't defined yet!

将该代码移动到函数中,其中有注释“其他初始化代码”FB.Event.subscribewindow.fbAsyncInit


答案 2

您收到此错误的另一个原因是,在 fbAsyncInit 定义括号之后缺少 ;

window.fbAsyncInit = function() {
};