jQuery点击只发生一次
问题描述:
我正在创建一个随机报价生成器。每次点击“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>");
}});
});
});
感谢您的帮助!
答
看来你对你的URL有一个错误:
http://crossorigin.me/http://api.forismatic ...
你看到在网络上检查每次点击按钮Ajax请求?
问候,
吉米
编辑:
的问题是,文本颜色: 这是一样的BG。
尝试添加此行JS:
$( “报价 ”),CSS(“ 色”, “黑色”)。
你的答案在这里:http://*.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements –
如果你console.log(结果)在你的ajax回调,当您多次点击时,控制台是否显示变量? – Cruiser
她说randColor已经到位,但她没有把它放在这里。 –