2011-07-25 68 views
4

所以我想在用戶點擊類似按鈕時做一些事件處理。FB.Event.subscribe不會觸發某些事件

我的Facebook按鈕被通過異步創建:

(function() { 
    var e = document.createElement('script'); e.async = true; 
    e.src = document.location.protocol + 
    '//connect.facebook.net/en_US/all.js'; 
    document.getElementById('fb-root').appendChild(e); 
}()); 

這偉大工程。

我有以下功能運行,以及:

window.fbAsyncInit = function() { 
    FB.init({status: true, cookie: true, xfbml: true}); 
    FB.Event.subscribe("xfbml.render", function() { 
     console.log('xfbml.render'); 
     FB.Event.subscribe("edge.create", function(targetUrl) { 
      console.log('edge.create'); 
     }); 
     FB.Event.subscribe("edge.remove", function(targetUrl) { 
      console.log('edge.remove'); 
     }); 
    }); 
}; 

到目前爲止,當我加載頁面時,我得到「xfbml.render」在控制檯中。然後我點擊像按鈕&我什麼都沒得到。

我想讓它吐出控制檯消息'edge.create'。

有沒有人有任何想法可能會導致此?

我已經把這個頁面放在一個可公開訪問的網站上(它目前在我的開發平臺上)&它仍然沒有工作。如果要求,我可以再次。

回答

8

爲了在您的網頁上使用XFBML,您必須將XML名稱空間屬性添加到頁面的根元素。沒有這個聲明,XFBML標記將不會在Internet Explorer中呈現。

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml"> 

接下來, 您加載使用標準的元素和調用SDK(FB.init())。您還必須在文檔中指定名爲fb-root的元素。

<div id="fb-root"></div> 

,然後確保你把你的應用程序ID內FB.init()函數,

FB.init({ 
    appId : 'YOUR APP ID', 
    status : true, // check login status 
    cookie : true, // enable cookies to allow the server to access the session 
    xfbml : true // parse XFBML 
    }); 

這裏是一個完整的工作代碼:

<!doctype html> 
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml"> 
<head> 
    <meta charset="utf-8"> 
    <title>Facebook Like Button</title> 
</head> 
<body> 
<div id="fb-root"></div> 
<script> 
    window.fbAsyncInit = function() { 
    FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true,xfbml: true}); 
    FB.Event.subscribe("edge.create", function(targetUrl) { 
     console.log('edge.create'); 
    }); 
    FB.Event.subscribe("edge.remove", function(targetUrl) { 
     console.log('edge.remove'); 
    }); 
    }; 
    (function() { 
    var e = document.createElement('script'); e.async = true; 
    e.src = document.location.protocol + 
     '//connect.facebook.net/en_US/all.js'; 
    document.getElementById('fb-root').appendChild(e); 
    }()); 
</script> 
<fb:like></fb:like> 
</body> 
</html> 
+0

原來,它是AppId的一部分。我希望避免使用它,因爲我們的網站是爲每個客戶端動態生成的,我們無法爲它們設置appIds。但這當然回答了我的問題。謝謝! –

+0

如果您不添加應用程序ID,JS SDK將無法工作,無論如何,它很高興回答您的問題,謝謝 –

4

只是以供將來參考:廢有一段時間,試圖讓iframe按鈕火災事件 - 沒有運氣,但與xfbml FB.Event.subscribe("edge.create", f);工作正常。