2017-09-15 54 views
3

我正在创建一个随机报价生成器。我已经使用quotesondesign.com的api完成了大部分工作,但最后我需要做的是在单击“新报价”按钮时将Twitter按钮更新为新报价。但它不会改变,我不知道为什么。Javascript更新推特按钮

$(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和忘记了很多东西一些愚蠢的事情......

回答

0

您需要从页面中删除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(); 
} 
+0

甜!非常感谢!! – Uberche

+0

@Uberche不客气!不要忘记,如果您发现它有帮助,您可以将我的答案标记为正确的答案。祝你未来的编码工作顺利! – trevor

+0

我以为我可以,但无法弄清楚,因为我的大脑显然不能很好地工作。我该如何去做呢? 没关系,找到它。 – Uberche

0

Twitter的链接不具备类“.twitter共享按钮”

编辑:更多详情。

在你的Codepen中,无论你正在使用哪个Twitter widget包,都会获取该链接并用iframe和其他几个嵌套元素替换它。用户最终点击的实际锚点被隐藏在底部,并且实际上并没有twitter分享按钮类。

+0

明白了,对信息的感谢!要研究正在构建的最终结果,并没有真正考虑该包将如何改变代码。 – Uberche