我正在尝试将 Facebook Like 按钮添加到我正在创建的小部件中。我用来将 Facebook 赞按钮添加到我的页面的代码如下:
小部件.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>
小部件.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 函数。
当我运行代码时,我收到一个错误:Uncaught ReferenceError: FB is not defined
即使按钮已创建。错误指向包含 FB.XFBML.parse 代码的行。我需要在我的 JavaScript 中做一些不同的事情吗?
最佳答案
我遇到了这个问题,并以与 Amry 提供的解决方案类似的方式解决了它,因此我将其发布在这里以防其他人需要使用它。
我最初假设在 fbAsyncInit 方法中进行的 FB 初始化调用会立即初始化,所以我也在 $(document).ready()
方法中编写了我对 FB 对象的使用.事实并非如此。 fbAsyncInit 在页面加载完成初始化后需要相当长的时间。这是我在网站上使用 jQuery 时的解决方案:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'your_app_id', // App ID
channelUrl : 'your channel',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
jQuery(document).trigger('FBSDKLoaded'); //This is the most important line to solving the issue
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=269187653191150";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
最后一个任务是简单地将您的 $(document).ready()
代码切换为事件的绑定(bind)。这适用于您使用 FB 对象的任何地方。
(function($) {
$(document).bind('FBSDKLoaded', function() {
//Code using the FB object goes here.
});
})(jQuery);
有一件事我还应该提到:Firefox 比 Chrome 等 Webkit 浏览器更能容忍这一点。我不明白为什么我的 jQuery 中没有一个在 Chrome 中正常工作……好吧,这就是原因。
我希望这对某人有帮助。
关于javascript - FB 是未定义的,即使我刚刚使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747668/