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

cjr*_*uck 5 javascript twitter url jquery pushstate

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

如何更新twitter使用的URL?

ram*_*uru 14

我成功使用了重新加载共享网址的新Twitter功能.

function updateTwitterValues(share_url, title) {
// clear out the <a> tag that's currently there...probably don't really need this since you're replacing whatever is in there already.
  $(container_div_name).html('&nbsp;'); 
  $(container_div_name).html('<a href="https://twitter.com/share" class="twitter-share-button" data-url="' + share_url +'" data-size="large" data-text="' + title + '" data-count="none">Tweet</a>');
twttr.widgets.load();
}
Run Code Online (Sandbox Code Playgroud)

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

<div id="twitter-share-section"></div>
Run Code Online (Sandbox Code Playgroud)

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


tig*_*tig 13

我想通了.以下是如何使这项工作.

一般的想法是:

  1. 在您的HTML设置中class,您<a>的Twitter分享按钮不是.twitter-share-button.也给了<a>一个style="display:none;".
  2. 在您希望显示Twitter分享按钮的HTML中,创建一个具有唯一性的<div>(或<span>)id.
  3. 在您的jQuery中,当您想要为twitter分享按钮设置数据时,您将:
    • the hidden, mis-named,来自步骤#1的'clone()`标签
    • 在此克隆上,根据需要设置data-urletc ...属性
    • style从克隆中删除属性(取消隐藏)
    • class将克隆更改为twitter-share-button
  4. append()这个克隆来自你<div>的第2步.
  5. 使用$.getScript()加载和运行的Twitter的JavaScript.这会将你的克隆<a>转换成一个<iframe>正确的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
Run Code Online (Sandbox Code Playgroud)

然后在你的客户端.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");
Run Code Online (Sandbox Code Playgroud)

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

  • 这不再适用了.iframe src仍然引用onload url.除了iframe的src之外,所有其他属性都会更改.不知道还能做什么. (2认同)