How to dynamically change facebook comments plugin url based on javascript variable?

徘徊边缘 提交于 2019-12-01 16:33:41

问题


I want to dynamically change the data-href for the fb comments plugin below based on a javascript variable. I'm running a flash swf file and am passing the new link for data-href into the html wrapper via a javascript function. When I do that, I want the fb comments plugin to refresh to the new data-href link.

<div style="float: left; padding-left:5px; min-height:500px" class="fb-comments" data-href="www.example.com" data-num-posts="20" data-width="380"></div>

Called javascript function passing in the new link for the comments plugin:

function changeCommentsUrl(newUrl){
// should refresh fb comments plugin for the "newUrl" variable
}

回答1:


This will load the initial comments box, the script will when executed will clear the comments div wrapper and replace html5 comments box with new url. JS SDK will then parse the new box.

JS SDK is required for this work. refer to https://developers.facebook.com/docs/reference/javascript/

fix for xfbml render from dom manipulation


<div id="comments">
<div style="float: left; padding-left:5px; min-height:500px" class="fb-comments" data-href="www.example.com" data-num-posts="20" data-width="380"></div>
</div>
<script>
function changeCommentsUrl(newUrl){
// should refresh fb comments plugin for the "newUrl" variable
document.getElementById('comments').innerHTML='';
parser=document.getElementById('comments');
parser.innerHTML='<div style="float: left; padding-left:5px; min-height:500px" class="fb-comments" data-href="'+newUrl+'" data-num-posts="20" data-width="380"></div>';
FB.XFBML.parse(parser);
}
</script>

user solved:

document.getElementById('comments').innerHTML='<div style="float: left; padding-left:5px; min-height:500px" class="fb-comments" data-href="'+link+'" data-num-posts="20" data-width="380"></div>'; 
FB.XFBML.parse(document.getElementById('comments'));




回答2:


I found the simplest and effective way to make your Facebook Comment box to recognize the individual URL of each page (particularly good for e-commerce sites).

Add this script to your top header portion of your website template (it generates de data-href value for your Comment Box div:

<script type="text/javascript" language="javascript">
  jQuery("#FC").attr("data-href", window.location.href.split("?")[0]); 
</script>

And then on your Comment Box div, add the id for the value generated on the javascript:

<div id="FC" class="fb-comments" data-href="" data-width="700" data-numposts="5" data-colorscheme="light">

Voilá. I dedicated so much time to crack this nut, I just had to share it for you to save some time for break! Cheers!



来源:https://stackoverflow.com/questions/11122633/how-to-dynamically-change-facebook-comments-plugin-url-based-on-javascript-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!