如何使用动态内容更新Twitter分享按钮URL?

我在应用程序开始时初始化推文按钮,在用户交互之后,使用HTML5 pushState更新当前窗口的位置,但是twitter按钮仍然在初始化时共享以前的URL。

如何更新twitter使用的URL?

我想出来了。 以下是如何使这项工作。

一般的想法是:

  1. 在您的HTML设置中,您的 for twitter share按钮的class不是.twitter-share-button 。 同时给出 a style="display:none;"
  2. 在您希望显示Twitter分享按钮的HTML中,创建具有唯一id

    (或 )。

  3. 在您的jQuery中,当您想要为twitter分享按钮设置数据时,您将:
    • ‘clone()来自步骤#1 the hidden, mis-named, `标签
    • 在此克隆上,根据需要设置data-url etc …属性
    • 从克隆中删除style属性(取消隐藏)
    • 将克隆的class更改为twitter-share-button
  4. 将此克隆从第2步append()

  5. 使用$.getScript()加载并运行Twitter的Javascript。 这会将您克隆的转换为并使用所有正确的goop。

这是我的HTML(在Jade中):

  a.twitter-share-button-template(style="display:none;", href='https://twitter.com/share=', data-lang='en', data-url='http://urlthatwillbe_dynamically_replaced', data-via='ckindel', data-text='Check this out!', data-counturl='http://counturlthatwillbe_dynamically_replaced') Share with Twitter #twitter-share-button-div 

然后在你的客户端.js:

 // the twitter share button does not natively support being dynamically // updated after the page loads. We want to give it a unique (social_id) // link whenver this modal is shown. We engage in some jQuery fun here to // clone a 'hidden' twitter share button and then force the Twitter // Javascript to load. // remove any previous clone $('#twitter-share-button-div').empty() // create a clone of the twitter share button template var clone = $('.twitter-share-button-template').clone() // fix up our clone clone.removeAttr("style"); // unhide the clone clone.attr("data-url", someDynamicUrl); clone.attr("data-counturl", someDynamicCountUrl); clone.attr("class", "twitter-share-button"); // copy cloned button into div that we can clear later $('#twitter-share-button-div').append(clone); // reload twitter scripts to force them to run, converting a to iframe $.getScript("http://platform.twitter.com/widgets.js"); 

我从这里得到了这个解决方案的主要线索: http : //tumblr.christophercamps.com/post/4072517874/dynamic-tweet-button-text-using-jquery

我成功使用了重新加载共享url的新Twitterfunction。

 function updateTwitterValues(share_url, title) { // clear out the  tag that's currently there...probably don't really need this since you're replacing whatever is in there already. $(container_div_name).html(' '); $(container_div_name).html(''); twttr.widgets.load(); } 

我的初始HTML只有一个用于共享链接的容器,如下所示:

 

每当我从ajax调用中获取新数据时,我只需调用updateTwitterValues()并传递新信息。 更多信息请访问https://dev.twitter.com/discussions/5642

twttr.widgets.load();

来自Twitter的Dev Docs 。

  The tweet button: