Я создаю генератор случайных цитат. Каждый раз, когда я нажимаю кнопку «Получить предложение», новая цитата должна быть сгенерирована из 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>");
}});
});
});
Спасибо за любую помощь !
Ваш ответ здесь: http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements –
, если вы console.log (результат) в вашем ajax callback, показывает ли консоль переменную, когда вы нажимаете несколько раз? – Cruiser
Она сказала, что randColor на месте, но она не поместила его здесь в фрагмент. –