首页 > 解决方案 > Getting jquery to add the content of two elements automatically to a button link

问题描述

I´m running this code, and I keep getting "undefined" when I click on my tweet button to redirect me to twitter. Any ideas on how to fix it and getting the desired outcome?

function startQuote() {
  $.getJSON(
    "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?",
    function (data) {
      // The data is an array of posts. Grab the first one.
      var post = data.shift();
      $("#author").text(post.title);
      $("#text").html(post.content);
      $("#tweet-quote").attr(
        "href",
        'https://twitter.com/intent/tweet?text="' +
        post.title.text +
        '"' +
        " - " +
        post.content.text
      );
    }
  );
}


window.onload = startQuote;

$("#new-quote").on("click", startQuote)

标签: javascriptjquery

解决方案


post.title.text and post.content.text are undefined

$("#tweet-quote").attr("href", "https://twitter.com/intent/tweet?text=\"" + post.title + "\"" + " - " + $(post.content).text());

code: https://codepen.io/peker-ercan/pen/MPayyE


推荐阅读