2016-09-27 84 views
0

我正在創建一個隨機報價生成器。每次點擊「Get Quote」按鈕時,都應該從API生成一個新報價,並且背景顏色會發生變化。不過,每次點擊時背景顏色都會發生變化,但只有第一次點擊按鈕時,引用纔會發生變化。jQuery點擊只發生一次

我的HTML如下:

<body> 
<div class="container-fluid"> 
    <div id="centerThis" style="background: transparent"> 
    <div id=target1> 
     <h1 class="text-center">Random Quote:</h1> 
     <div class="quote"> 
     <blockquote> 
      <p id="quoteT">Humans are allergic to change. They love to say, 'We've always done it this way.' I try to fight that. That's why I have a clock on my wall that runs counter-clockwise.</p> 
      <footer id="quoteA">Grace Hopper</footer> 
     </blockquote> 
     </div> 
     <div class="row"> 
     <div class="col-xs-2"> 
      <a href="https://twitter.com/?lang=en" target='_blank'><button onclick="tweetIt()" class="btn myButton colorButton"><i class="fa fa-twitter" aria-hidden="true"></i></button></a> 
     </div> 
     <div class="col-xs-2"> 
      <a href="https://www.tumblr.com/dashboard" target='_blank'><button onclick="tweetIt()" class="btn myButton colorButton"><i class="fa fa-tumblr" aria-hidden="true"></i></button></a> 
     </div> 
     <div class="col-xs-4"> 
     </div> 
     <div class="col-xs-4"> 
      <button id = "getQuote" class = "btn colorButton"> 
     Get Quote 
     </button> 
     </div> 
     </div> 
    </div> 
    <div id="target2"> 
     <h5 id="byAnna" class="text-center">by <a href="http://codepen.io/annajolly/" target="_blank">anna</a></h5> 
    </div> 
    </div> 
</div> 
</body> 

我的jQuery看起來是這樣的(我離開了出來randColor和代碼等一些非重要部分):

$(document).ready(function() { 
    $("#target1").css("color",randColor); 
    $("#target2").css("background", randColor); 
    $("body").css("background", randColor); 
    $(".colorButton").css("background", randColor); 
    $("#getQuote").on("click", function(){ 
    randColor = getRandomColor(); 
    $("#target1").css("color",randColor); 
    $("#target2").css("background", randColor); 
    $("body").css("background", randColor); 
    $(".colorButton").css("background", randColor); 
    $.ajax({url: "http://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en", success: function(result){ 
      $(".quote").html("<blockquote><p>" + result.quoteText + "</p><footer>" + result.quoteAuthor + "</footer></blockquote>"); 
     }}); 
    }); 
}); 

感謝您的幫助!

+0

你的答案在這裏:http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements –

+0

如果你console.log(結果)在你的ajax回調,當您多次點擊時,控制檯是否顯示變量? – Cruiser

+0

她說randColor已經到位,但她沒有把它放在這裏。 –

回答

0

看來你對你的URL有一個錯誤:

http://crossorigin.me/http://api.forismatic ...

你看到在網絡上檢查每次點擊按鈕Ajax請求?

問候,

吉米

編輯:

的問題是,文本顏色: 這是一樣的BG。

嘗試添加此行JS:

$( 「報價 」),CSS(「 色」, 「黑色」)。