javascript - 在 Twitter 上引用 Object.textContent 的内容

标签 javascript jquery html

我已经构建了一个页面,在其中从 API 中提取随机引用,并且所有内容都在这方面工作,但我似乎无法提取 textContent 并将其附加到推文按钮。

这是我的代码:

HTML

<div id="quote-box">
  <div id="quote-copy">
    <i class="fa fa-quote-left" id="quotation"> </i> 
    <span class="text" id="random-quote"></span>
  </div>
  <div id="quote-author">
    - <span class="author"></span>
  </div>
  <div id="quote-buttons">
    <a class="button" id="instagram" title="follow me on IG!" target="_blank" href="https://www.instagram.com/dopeland/"><i class="fa fa-instagram" aria-hidden="true"></i> Instagram</a>
    <a class="button" id="tweet-this" title="Tweet This Quote!" href="https://twitter.com/share" target="_blank" data-size="large"><i class="fa fa-twitter" aria-hidden="true"></i> Tweet This!</a>
    <a class="button" id="get-quote" title="Generate a new quote!" href="">New Quote</a>
  </div>
</div>


Javascript

function getQuote(){
    $.ajax({
      url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
      success: function(data) {
        var post = data.shift();
        $('.author').text(post.title);
        $('.text').html(post.content);
      },
      cache: false
    });
  };

function changeColor(){
  var colors = ['#7A918D', '#93B1A7', '#99C2A2', '#C5EDAC', '#DBFEB8'];
  var randNum = Math.floor(Math.random() * (colors.length - 0));

  document.body.style.background = colors[randNum];
  $('#quotation').css('color', colors[randNum]);
};



$(document).ready(function() {
  getQuote(); 
  changeColor();

  var randomQuote = $('#random-quote')["0"].textContent;

  $('#tweet-this').click(function(){
    $(this).attr('href', "https://twitter.com/intent/tweet?text=" + randomQuote);
  });

  $('#get-quote').on('click', function(e) {
    e.preventDefault();
    getQuote();
    changeColor();
  });
});


所以我的问题是,每当我单击推文按钮时,我只会返回链接“https://twitter.com/intent/tweet?text=

您还可以在这里查看我的CodePen:https://codepen.io/dopeland/pen/XgwNdB

最佳答案

var randomQuote = $('#random-quote')["0"].textContent; 移至 click 监听器内

像这样:

$('#tweet-this').click(function(){
    var randomQuote = $('#random-quote')["0"].textContent;
    $(this).attr('href', "https://twitter.com/intent/tweet?text=" + randomQuote);
});

randomQuote 在开始时分配一次(设置为值 "")。即使您正在调用 click 监听器,引用的文本也永远不会写入 randomQuote 并始终保持为 ""

fork 和固定代码笔:https://codepen.io/eqwert/pen/owraVK

关于javascript - 在 Twitter 上引用 Object.textContent 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45198144/

相关文章:

javascript - 如何仅向 vuejs 中的单击按钮添加加载?

html - ItextSharp 支持 HTML 和 CSS

javascript - 从 AJAX 调用填充数组并将其返回到调用函数

javascript - 使用 Javascript 跳过 HTTP 身份验证?

javascript - 如何使用 Ajax 解决 'NS_ERROR_ILLEGAL_VALUE' 错误?

javascript - 动态添加和编辑行

javascript - 如何设置 JQuery 数据表

html - 使用 Dart 编辑 CSS

javascript - 如何按顺序(不是索引)迭代类似数组的对象?

jquery - Rails-jquery-autocomplete 搜索 school_name 但保存 school_id