调整twitter按钮而不重新加载?

时间:2016-02-08 17:52:25

标签: javascript jquery twitter

我有一个随机引用生成器,可以发布显示的随机引用,一切正常,除了每次生成新引号时,twitter按钮都必须重新加载,并且它看起来不太好。有没有办法在没有烦人重载的情况下更改iframe?

指向codepen- http://codepen.io/Davez01d/pen/gPegpd

的链接

html -

<div class="row vert-space-25 vert-bottom-space-25 text-center"><!--twitterbutton-->
  <div id="twitter-button" class="col-xs-12">
    <a class="twitter-share-button" data-size="large">Tweet</a>
    <!--javascript for twitter button-->
    <script>window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))returnt;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));</script>
  </div>
</div><!--twitterbutton-->

javascript -

var quotes = [
  { text: '"She got a big booty so I call her big booty"', author: '2Chainz'}, 
  { text: '"Success consists of going from failure to failure without loss of enthusiasm."', author: 'Winston Churchill'}, 
  { text: '"If you\'re going through hell, keep going."', author: 'Winston Churchill'},
  { text: '"Success is not final, failure is not fatal: it is the courage to continue that counts."', author: 'Winston Churchill'},
  { text: '"Nearly all men can stand adversity, but if you want to test a man\'s character, give him power."', author: 'Abraham Lincoln'},
  { text: '"Whatever you are, be a good one."', author: 'Abraham Lincoln'},
  { text: '"I walk slowly, but I never walk backward."', author: 'Abraham Lincoln'},
];

$("#newQuote").click(function() { 
  var randomNum = Math.floor(Math.random() * quotes.length); //get random number between 0 and quotes.length
  $("#quote").html(quotes[randomNum].text); //insert the random quote into the html
  $("#author").html(" -" + quotes[randomNum].author); //insert the author into the html
  createButton(); //creates a new twitter button, when shared will have the displayed quote and author
});

var createButton = function () {
  $('iframe.twitter-share-button,a.twitter-share-button').remove(); //removes the iframe generated by twitter widgets js
  var twtr = '<a class="twitter-share-button"></a>';
  $('#twitter-button').append(twtr); //creates new twitter button
  $('.twitter-share-button').attr('href', 'https://twitter.com/share') 
  .attr('data-text', $('#quote').html()+$('#author').html()).attr('data-size', 'large'); //sets attributes on the new twitter button so when shared it displays the quote and author
  twttr.widgets.load(); //reloads the js for the twitter button
};

1 个答案:

答案 0 :(得分:2)

不。出于安全原因,页面上的JavaScript无权访问位于其他域上的该页面上的iframe。如果您同时控制主机页面和iframe中的页面,则可以使用postMessage在它们之间传递消息。

但是,您是否需要使用Twitter iframe按钮?还有其他方法可以通过JavaScript与Twitter分享。一种简单的方法就是撰写共享网址:https://twitter.com/share?text=xxx&url=yyy

xxx是您的推文文字,yyy是指向文字链接的网址。一定要对xxx和yyy进行url编码。

所以你可以使用你自己的按钮或链接,并完成同样的事情。