2017-01-24 36 views
1

我有一個隨機報價發生器(http://codepen.io/anon/pen/wgqWgo),並試圖鳴叫報價的時候,我得到以下結果:Twitter的按鈕不啁啾正確

enter image description here

我沒有連接我的報價正確我承擔我的功能。對於JavaScript的新手來說,很難說出什麼。我已經在這方面進行了廣泛的搜索,似乎無法找到解決方案。

我的HTML:

<div class="row"> 
        <div class="col-12 buttons"> 
         <a class="twitter-share-button" href="http://twitter.com/share" target="_blank"><button type="button" class="btn btn-outline-danger" onclick="tweetIt()"><i class="fa fa-twitter" aria-hidden="true"></i></button></a> 
         <button type="button" class="btn btn-outline-danger" onclick="newQuote()">Quote</button> 
        </div> 
       </div> 

    <div class="row"> 
        <div class="col-12"> 
         <div id="quoteDisplay" class="writing"> 
          <!-- Quotes here --> 
         </div> 
        </div> 
       </div> 

我的javascript:

var quotes = [ 
    "There is nothing to writing. All you do is sit down at a typewriter and bleed.", 
    "Happiness in intelligent people is the rarest thing I know.", 
    "The world breaks everyone, and afterward, some are strong at the broken places." 
] 
function newQuote() { 
    var randomNumber = Math.floor(Math.random() * (quotes.length)); 
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber]; 
}; 

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

回答

0

是在你的代碼中使用了該鏈接,是一個在<a>標籤。

你不想那樣。該鏈接沒有任何數據被傳入,因此,Twitter默認URL爲twitter.com/intent/tweet?url=&original_referer=,它會將文本生成爲您來自的URL。 (在你的情況下,這是你的本地)。

有沒有必要換twitter的button一個的<a>標記,因爲你使用的是oncick() function.

下面的代碼似乎做你要完成的任務。

首先修改HTML如下:

<div class="row"> 
        <div class="col-12 buttons"> 
         <button type="button" class="btn btn-outline-danger" onclick="tweetIt()">Tweet</button> 
         <button type="button" class="btn btn-outline-danger" onclick="newQuote()">Quote</button> 
        </div> 
       </div> 

    <div class="row"> 
        <div class="col-12"> 
         <div id="quoteDisplay" class="writing"> 
          <!-- Quotes here --> 
         </div> 
        </div> 
       </div> 

和你.js應該是這樣的:

var quotes = [ 
    "There is nothing to writing. All you do is sit down at a typewriter and bleed.", 
    "Happiness in intelligent people is the rarest thing I know.", 
    "The world breaks everyone, and afterward, some are strong at the broken places." 
] 
function newQuote() { 
    var randomNumber = Math.floor(Math.random() * (quotes.length)); 
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber]; 
}; 

function tweetIt(){ 
var randomNumber = Math.floor(Math.random() * (quotes.length)); 
window.open("https://twitter.com/intent/tweet?text=" + quotes[randomNumber]); 
} 
+0

非常感謝你。以一種乾淨而簡單的方式與我一直苦苦掙扎的問題幫助了我。 – YoungCoder