2017-04-18 45 views
0

我試圖發佈文本我從執行getJSON命令的函數獲取,我創建的推文按鈕打開twitter但沒有文本,我希望它自動「粘貼」引用網頁目前正在顯示。我的基本的html代碼如下:將文本從一個變量添加到推文

<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button> 

<div class="col-md-8 show boxed text-center"> Text </div> 

<div class="col-md-5 text-center author"> auth 
</div> 

<a class="tw-button" href="https://twitter.com/intent/tweet/?text=" data-size="large" target="_blank"> 
    <button type="twbutton" class="btn btn-primary">Tweet quote</button> 
</a> 

我的JS:

$(document).ready(function() { 
    gQuote(); 

    function gQuote() { 
    $.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", 
     function(data) { 
     var Quote = data.quoteText; 
     var Author = data.quoteAuthor; 
     var quoteShow = "" 
     var quoteAuthor = "" 
     quoteShow += "<h3 class='text-center'>" + Quote + "</h3>" 
     quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>" 
     $(".show").html(quoteShow); 
     $(".author").html(quoteAuthor); 

     }); 

    }; 

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

    }); 
}); 

據我所知,Quote變量被先前的功能中創建的,我不太清楚,我怎麼能「扛」它朝着twitter按鈕。 我正在使用codepen,所以"target:_blank"是必須的。

+0

考慮這個例子:https://jsfiddle.net/L05c1c7y/1/ - 聲明一個變量'var'意味着它是在本地範圍內(該功能'gQuote()'在你的例子只是訪問)。通過刪除'var',你可以全局訪問它。 – Santi

回答

0

Quote變量對於$ .getJSON中的回調是本地的。 其中一個(也是最簡單的)解決方案是將'var Qoute'聲明轉換爲$(document).ready回調的回調,以便'$(「。tw-button」)可以訪問它。click '在右手搜索期間通過範圍鏈回調。儘管如此,這對大規模代碼來說並不是很好。

$(document).ready(function() { 
    gQuote(); 

    var Quote; //Declare variable here 

    function gQuote() { 
     $.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(data) { 

      Quote = data.quoteText; //Set it here 

      var Author = data.quoteAuthor; 
      var quoteShow = "" 
      var quoteAuthor = "" 
      quoteShow += "<h3 class='text-center'>" + Quote + "</h3>" 
      quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>" 
      $(".show").html(quoteShow); 
      $(".author").html(quoteAuthor); 

     }); 
    }; 

    $("#quoteClick").on("click",function() { 
     gQuote(); 
    }); 

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

}); 
+0

工作。謝謝! – arziankorpen

0

如果我沒有弄錯,所有你需要做的就是聲明你的變量QuoteAuthor以外的gQuote()函數。在gQuote()內部,您可以將它們分配給他們,並將其最新值傳遞給$(".tw-button").click()事件。 使確定你有JSON對象和解析的數據。


我做了一些類似freecodecamp項目。如果你有困難,看看here

相關問題