使用jQuery开发随机引用生成器遇问题:初始引用与推特按钮故障
Hey there! Let's work through those two bugs you're facing with your freeCodeCamp Random Quote Machine. I've tackled this exact challenge before, so let's break it down step by step.
1. Initial Quote Not Loading on Page Load
The main issue here is likely how you're handling the API response and ensuring the fetch runs on page ready. The Quotes on Design API returns an array of post objects, so you need to target the first item in that array to get your quote. Also, jQuery might cache the request by default, which can cause unexpected behavior.
Fix:
Create a reusable function to fetch quotes, then call it immediately when the page loads. Here's how to adjust your code:
$(document).ready(function() { // Reusable function to fetch and display a quote function loadNewQuote() { // Use $.ajax instead of $.getJSON to disable caching $.ajax({ url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=", dataType: "json", cache: false, success: function(data) { // Extract quote content and author from the first post in the array const quoteContent = data[0].content; const quoteAuthor = data[0].title; // Update your message element with the quote $(".message").html(quoteContent); // Optional: Add an author element if you have one $(".author").text(`— ${quoteAuthor}`); // We'll update the Twitter button here too (for your second issue) updateTwitterLink(quoteContent, quoteAuthor); }, error: function() { // Fallback if the API fails $(".message").html("Oops! Couldn't load a quote. Refresh to try again."); } }); } // Call the function right away for the initial quote loadNewQuote(); // Add click handler for your "New Quote" button (if you haven't already) $(".new-quote-btn").click(function() { loadNewQuote(); }); });
Key notes:
- The API returns an array, so we use
data[0]to access the random quote object. - Disabling
cacheensures you get a fresh quote every time, including on page load. - Adding an error handler prevents your app from breaking silently if the API is down.
2. Twitter Button Not Working
This usually happens because the Twitter share link isn't being updated with the current quote, or the quote text isn't properly encoded for URLs. Twitter's intent URL requires the text parameter to be URI-encoded to handle spaces and special characters.
Fix:
Add a function to update the Twitter button's href attribute every time a new quote loads. Here's the function to add (and we already called it in the success handler above):
function updateTwitterLink(quoteContent, quoteAuthor) { // Convert HTML quote content to plain text (to avoid tags in the tweet) const plainQuote = $(quoteContent).text().trim(); // Build the full tweet text const tweetText = `"${plainQuote}" — ${quoteAuthor}`; // Encode the text for the URL const encodedText = encodeURIComponent(tweetText); // Update the Twitter button's href $(".twitter-button").attr("href", `https://twitter.com/intent/tweet?text=${encodedText}`); }
Make sure your Twitter button is an <a> tag in your HTML (not just a button without a link):
<a href="#" class="twitter-button" target="_blank">Tweet This Quote</a>
If you want to open the tweet in a popup window instead of a new tab, add this click handler:
$(".twitter-button").click(function(e) { e.preventDefault(); window.open($(this).attr("href"), "TweetQuote", "width=550,height=420"); });
Putting it all together, your code should now load an initial quote on page load and let users tweet the current quote without issues. Test it out on Codepen, and let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者user9542625

