JavaScript更新Twitter按钮



我正在努力创建一个随机报价生成器。我将其主要使用QUATESONDESIGN.com的API完成,但是我需要做的最后一件事是在我单击"新报价"按钮时将Twitter按钮更新到新报价中。但这不会改变,我不确定为什么。

$( document ).ready(function() { 
  //get Quote And call to update twitter Button
  $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) { 
    $("#quote-content").html(a[0].content); 
    $("#quote-title").text(a[0].title);
    updateTweet(a);
  });
  //new Quote and update Twitter
  $('#newButton').on('click', function() {
    $.ajax( {
      url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=',
      success: function(a) {
        $('#quote-content').html(a[0].content);
        $('#quote-title').text(a[0].title);
        updateTweet(a);
      },
      cache: false
    });
  });
  //update twitter button function
  function updateTweet(a) {
    var thisQuote = a[0].content.replace(/</?[^>]+(>|$)/g, "");
    var thisQuoteTitle = a[0].title;
    $(".twitter-share-button").attr("href", "https://twitter.com/intent/tweet?text=" + thisQuote + "- " + thisQuoteTitle);
  }
});

这是我正在研究的Codepen:https://codepen.io/uberche/pen/rlbjbp

我意识到它丑陋且无法正确设置,只是试图使功能在更改样式之类的情况下工作。任何帮助,将不胜感激。抱歉,如果我忘了包括一些愚蠢的事情,仍然学习JavaScript并忘记了很多事情...

您需要从页面上删除IFRAME,附加一个新的<a>元素,其中要在推文中使用的值,然后致电twttr.widgets.load()

使您的代码如下(在您的Codepen中进行了测试和确认):

// New Quote and Update Twitter
$('#newButton').on('click', function() {
  $.ajax(
    'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=',
    {
      success: function(a) {
        $('#quote-title').text(a[0].title);
        $('#quote-content').html(a[0].content);
        updateTweet(a);
      },
      cache: false
    }
  );
});
//Twitter Button Update
function updateTweet(a) {
  var thisQuote = a[0].content.replace(/</?[^>]+(>|$)/g, "");
  var thisQuoteTitle = a[0].title;
  // Remove the iframe
  $('#socialMore iframe').remove();
  // Generate new markup
  $('<a>', {
    class: 'twitter-share-button',
    id: 'tweet_btn',
    href: 'http://twitter.com/intent/tweet',
    'data-text': thisQuote + "- " + thisQuoteTitle
  }).appendTo('#socialMore');
  // Reload the widget
  twttr.widgets.load();
}

Twitter链接没有类。

编辑:更多细节。

在您的Codepen中,无论您要拉到的Twitter小部件软件包如何取用该链接,并用iframe和其他几个嵌套元素代替它。用户最终点击的实际锚位于底部,并且实际上没有Twitter-Share-button类。

最新更新