随机引用与jQuery



我正在为freeCodeCamp做一个"随机报价机"挑战,并使用codepen。对我来说,jQuery部分是很难解决的部分。Mi代码运行良好,除了两个问题:

  1. 页面加载完成后,我无法设置初始问候语
  2. 我的推文按钮不起作用

我的 JS 文件:

$(document).ready(function() {
// Initial quote not working
let initQuote = $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=", function (data) {
$(".message").html(data[0].content + " — " + data[0].title);
});
$.(".message").append(initQuote);
// Get quote button working ok
$(".btn-quote").on("click", function() {
$.ajaxSetup({ cache: false });
$.getJSON(
"https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=",
function(data) {
$(".message").html(data[0].content + " — " + data[0].title);
}
);
});
// Stuck on tweet button, not working
$(".btn-twitter").on('click', function (event) {
event.preventDefault();
window.open('https://www.twitter.com/intent/tweet?text=' + encodeURIComponent( + ' --'))
});
});

你可以在这里看到我的笔

欢迎任何建议

获取初始报价是一个异步调用,因此回调将在追加值运行:

// This will run before your network request returns
`$.(".message").append(initQuote);`
// Then the network request will finish, and call this callback to set the content:
let initQuote = $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=", function (data) {
$(".message").html(data[0].content + " — " + data[0].title);
});

这是工作 AOK。


你的推特按钮真的很接近。您只需要添加报价:$(".message").text()

window.open('https://www.twitter.com/intent/tweet?text=' + encodeURIComponent($(".message").text() + ' --'))


合 https://codepen.io/anon/pen/VxywZm?editors=0010

最新更新