我正在努力创建一个随机报价生成器。我使用 quotesondesign.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);
}
});
这是我正在处理的代码笔:https://codepen.io/Uberche/pen/RLbjbp
我意识到它很难看,而且设置不当,我只是想在改变样式等之前让功能正常工作。任何帮助,将不胜感激。对不起,如果这是我忘记包含的一些愚蠢的东西,我还在学习 javascript 并且忘记了很多东西......
最佳答案
您需要从页面中删除 iframe,附加一个新的 <a>
元素包含您要在推文中使用的值,然后调用 twttr.widgets.load()
.
使您的代码如下(在您的代码笔中测试和确认):
// 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();
}
关于Javascript 更新推特按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46245221/