更新FB:像使用JavaScript动态地使用URL

RZK*_*ZKY 11 javascript facebook xfbml

我想将URL更改为类似于FB:Like按钮动态使用javascript.

现在我只能更改fb:like标签的href属性(我已粘贴下面的代码).但只是改变href似乎不起作用.也许我必须重新启动FB:Like按钮,但到目前为止我无法弄清楚如何...

function update_share(container, url) {
  // update fb:like href value
  var container = container[0] || document.body;
  var button = container.getElementsByTagName('fb:like');
  button[0].setAttribute('href', url);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.谢谢..

Moh*_*rif 23

它对我来说也适用于XFBML标签而不使用FB iframe,甚至可以使用多个FB调用AJAX

您只需要将整个XFBML代码包装在JS/jQuery中并解析它,如下所示:

$('#like').html('<fb:like href="' + url + '" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />');
if (typeof FB !== 'undefined') {
    FB.XFBML.parse(document.getElementById('like'));
}
Run Code Online (Sandbox Code Playgroud)

HTML代码:

<span id="like"></span>
Run Code Online (Sandbox Code Playgroud)

这对于更多的人来说会有所帮助:)

  • 我测试了这个解决方案并且工作正常.谢谢. (2认同)

小智 8

另一种方案:

而不是你的fb:like对象,在你的html中写一个FB iframe,如下所示:

<iframe id="face" name="face" src="http://www.facebook.com/plugins/like.php?href=http://www.google.fr&layout=button_count&show_faces=false&width=400&action=like&font=arial&colorscheme=light" allowtransparency="true" style="border: medium none; overflow: hidden; width: 400px; height: 21px;" frameborder="0"scrolling="no"></iframe>
Run Code Online (Sandbox Code Playgroud)

现在你可以用这个函数改变javascript:

function setUrl(url)
{
    sUrl = url;
    url = "http://www.facebook.com/plugins/like.php?href="+sUrl+"&layout=button_count&show_faces=false&width=400&action=like&font=arial&colorscheme=light";
    document.getElementById('face').setAttribute('src', url);
    //alert("url : "+url);
}
Run Code Online (Sandbox Code Playgroud)

更改src时,会更新FB iframe.


And*_*aev 8

对于reinit社交按钮,我使用此代码:

//Facebook like
if(typeof(FB) !== 'undefined')
     FB.XFBML.parse(document.getElementById('fblike'));

//Google plus one
if(typeof(gapi) !== 'undefined') {
    gapi.plusone.render(document.getElementById('gplus'),{
        'href':location.href,
        'annotation':'bubble',
        'width': 90,
        'align': 'left',
        'size': 'medium'
    });
}

//Twitter tweet button
if(typeof(twttr) !== 'undefined') {
    $('.twitter-share-button').attr('data-url',location.href);
    twttr.widgets.load();
}
Run Code Online (Sandbox Code Playgroud)

使用这样的html代码:

<div style="float:left;margin-top: 5px;width:80px;">
    <div id="gplus" class="g-plusone" data-size="medium"></div>
</div>
<div style="float:left;margin-top:5px;width:90px;">
    <a href="https://twitter.com/share" class="twitter-share-button">Tweet</a>
</div>
<div style="float:left;margin-top:5px;width:80px;" id="fblike">
    <fb:like send="false" layout="button_count" width="100" show_faces="false"></fb:like>
</div>
Run Code Online (Sandbox Code Playgroud)