2017-07-19 25 views
1

的报价我已经建立了一个页面,我从API中随机引用了一切,并且都在这方面工作,但我似乎无法拉动textContent并将其附加到推文按钮。推出来自Object.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(); 
    }); 
}); 


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

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

回答

0

移动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,并始终保留为""

分叉和固定密码:https://codepen.io/eqwert/pen/owraVK