Javascript 如何向 AJAX 驱动的页面添加 Facebook 的“喜欢”按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4219729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:26:06  来源:igfitidea点击:

How to add a Facebook "Like" button to an AJAX driven page

javascriptjqueryajaxfacebook

提问by nokturnal

I have trawled the net and Stack Overflow and have not found an adequate answer to this question. Before I start the trial and error process of finding my own solution, I thought I would turn to the Stack Overflow braintrust and see if there was already a successful implementation.

我已经搜索了网络和 Stack Overflow,但没有找到这个问题的适当答案。在我开始寻找自己的解决方案的试错过程之前,我想我会求助于 Stack Overflow 智囊团,看看是否已经有一个成功的实现。

I have an AJAX powered page that degrades properly for non-javascript browsers and SEO. Each click in the AJAX version can be represented by a unique URL.

我有一个 AJAX 驱动的页面,该页面对于非 JavaScript 浏览器和 SEO 会正确降级。AJAX 版本中的每次点击都可以由一个唯一的 URL 表示。

What I want to do is to dynamically change the HREF of the button. I do understand that this tag is converted to standard HTML at runtime (namely into a nasty table / iframe layout).

我想要做的是动态更改按钮的 HREF。我知道这个标签在运行时被转换为标准 HTML(即转换为一个令人讨厌的表格/iframe 布局)。

I was just wondering if anyone had any insight as to how to implement this FB like button onto AJAX powered pages?

我只是想知道是否有人对如何在 AJAX 驱动的页面上实现这个类似 FB 的按钮有任何见解?

Cheers in advance :)

提前干杯:)

EDIT:

编辑:

What do you think of this method I just hacked together? See any huge problems with it?

你觉得我刚刚一起破解的这个方法怎么样?看到它有什么大问题了吗?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="JS/jquery/jquery.js" type="text/javascript"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

    <script language="javascript" type="text/javascript">
        $("document").ready
        (
            function ()
            {
                CreateNewLikeButton("http://www.yahoo.com")

                $("a#ChangeToGoogle").click
                (
                    function (e)
                    {
                        e.preventDefault();
                        CreateNewLikeButton("http://www.google.ca")
                    }
                );

            }
        );

        function CreateNewLikeButton(url)
        {
            var elem = $(document.createElement("fb:like"));
            elem.attr("href", url);
            $("div#Container").empty().append(elem);
            FB.XFBML.parse($("div#Container").get(0));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
        <fb:like href="http://www.NEVER_LINK_TO_THIS_12345.com"></fb:like>
    </div>
    </form>
</body>

</html>

回答by Zorox

SIMPLE SOLUTION

简单的解决方案

Just parse trigger the parse function when load complete.

只需在加载完成时 parse 触发 parse 函数。

If you're using jQuery, there's a real easy and slick solution to this problem:

如果您使用的是 jQuery,那么这个问题有一个真正简单而巧妙的解决方案:

$(document).ajaxComplete(function(){
    try{
        FB.XFBML.parse(); 
    }catch(ex){}
});

http://developers.facebook.com/docs/reference/plugins/like/

http://developers.facebook.com/docs/reference/plugins/like/

回答by nokturnal

This is the solution I ended up going with:

这是我最终采用的解决方案:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="JS/jquery/jquery.js" type="text/javascript"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

    <script language="javascript" type="text/javascript">
        $("document").ready
        (
            function ()
            {
                CreateNewLikeButton("http://www.yahoo.com")

                $("#ChangeToGoogle").click
                (
                    function (e)
                    {
                        e.preventDefault();
                        CreateNewLikeButton("http://www.google.ca")
                    }
                );

            }
        );

        function CreateNewLikeButton(url)
        {
            var elem = $(document.createElement("fb:like"));
            elem.attr("href", url);
            $("#Container").empty().append(elem);
            FB.XFBML.parse($("#Container").get(0));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
        <fb:like href="http://www.NEVER_LINK_TO_THIS_12345.com"></fb:like>
    </div>
    </form>
</body>

</html>

回答by rycaps

This is how I handled this situation when I ran into it - seems to work well.

当我遇到这种情况时,这就是我处理这种情况的方式 - 似乎运作良好。

// Set Facebook Like Button with jQuery
setFBLikeButtons = function (container,url,send,layout,width,show_faces,font) {
  // Set Default Args
  if(!send) { send = "false"; }
  if(!layout) { layout = "button_count"; }
  if(!width) { width = "100"; }
  if(!show_faces) { show_faces = "false"; }
  if(!font) { font = "arial"; }

  $(container).empty(); // Remove current like button
  $(container).html('<fb:like href="'+url+'" send="'+send+'" 
       layout="'+layout+'" width="'+width+'" show_faces="'+show_faces+'" 
       font="'+font+'"></fb:like>');
  FB.XFBML.parse(); // This is the magical syrup
}

回答by Peter Bailey

You're making this hard on yourself - just render a new iframe-based one.

你让自己很难做到这一点 - 只需渲染一个新的基于 iframe 的。

<html>
<head>
  <title>Test Page</title>

  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">  

  $(function()
  {
    $( '#ChangeToGoogle' ).click( function( event )
    {
      event.preventDefault();

      $( '#Container' ).empty().append( $('<iframe />')
        .attr( 'src', 'http://www.facebook.com/plugins/like.php?href=www.google.com&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' )
        .attr( 'scrolling', 'no' )
        .attr( 'frameborder', 'no' )
        .attr( 'style', 'border:none; overflow:hidden; width:450px; height:80px;' )
        .attr( 'allowTransparency', 'true' )        
      );            
    });
  });

  </script>
</head>

<body>
    <form id="form1" runat="server">
    <a id="ChangeToGoogle" href="#">Change To Google</a>
    <div id="Container">
      <iframe src="http://www.facebook.com/plugins/like.php?href=www.yahoo.com&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80"
        scrolling="no" frameborder="0"
        style="border:none; overflow:hidden; width:450px; height:80px;"
        allowTransparency="true">
      </iframe>
    </div>
    </form>
</body>

回答by Csáky Attila

create like button

创建类似按钮

<head>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
window.onload = function(){
var divs = document.getElementsByTagName("span");
for(var i=0; i<divs.length i++){
if(divs[i].className == "likes"){
if(divs[i].title){ var Href = divs[i].title; }else{ var Href = window.location; }
var fb_like = document.createElement("fb:like");
fb_like.setAttribute("href", Href);
fb_like.setAttribute("layout", "box_count");
fb_like.setAttribute("show_faces", "false");
fb_like.setAttribute("width", "55");
document.getElementById("likes2").appendChild(fb_like);
}
}
}
</script>
</head>
<body>
<span class="likes" title="www.bzzs.me"></span>
</body>

回答by Devin Walker

Load it after the window loads, this is what works for me:

在窗口加载后加载它,这对我有用:

$(window).load(function(){
     $.getScript('http://connect.facebook.net/en_US/all.js', function() {
          try{
                FB.XFBML.parse();
            } catch(ex) {}
      });
});

回答by Simon_Weaver

If you're using the jQuery Mobile frameworkyou can run the same code as the accepted answer in the pagecontainershowevent which jQuery Mobile uses when it displays a new page.

如果您使用的是jQuery Mobile 框架,则可以在pagecontainershowjQuery Mobile 在显示新页面时使用的事件中运行与接受的答案相同的代码。

// initialize new pages
$(document).on("pagecontainershow", (e, ui) =>
{
    try
    {
        FB.XFBML.parse();
    } catch (ex) { }
});