每当div单击时,此代码就会以随机顺序随机排列三个数组。我希望两个数组“ quotes”和“ authors”显示相同的随机数组顺序。我希望“第三”等于“-第三”,“第一”等于“-第一”,或者当x是随机的时,引号[x] == authors [x]。
还有没有一种简单的方法来组合.ready和.click函数,所以我没有在两者中放入完全相同的代码?
var colors = ["#3b609b", "#9b3b3b", "#3b9b81", "#7da5a4"];
var quotes = ["First", "Second", "Third", "Fourth"];
var authors = ["-First", "-Second", "-Third", "-Fourth"];
$(document).ready(function() {
//Variables to shuffle through "colors", "quotes" and "authors" arrays.
var rand = Math.floor(Math.random() * colors.length);
var rand2 = Math.floor(Math.random() * quotes.length);
var rand3 = Math.floor(Math.random() * authors.length);
//Display quotes/authors and change background colors.
$("body, .button, .social").css("background-color", colors[rand]);
$(".quote").html(quotes[rand2]).css("color", colors[rand]);
$(".author").html(authors[rand3]).css("color", colors[rand]);
$(".button").click(function() {
//Variables to shuffle through "colors", "quotes" and "authors" arrays.
var rand = Math.floor(Math.random() * colors.length);
var rand2 = Math.floor(Math.random() * quotes.length);
var rand3 = Math.floor(Math.random() * authors.length);
//Display quotes/authors and change background colors when div is clicked.
$("body, .button, .social").css("background-color", colors[rand]);
$(".quote").html(quotes[rand2]).css("color", colors[rand]);
$(".author").html(authors[rand3]).css("color", colors[rand]);
});
});
最佳答案
使用包含每个引号的所有内容的对象,然后简单地随机选择一个对象,即可访问该对象的所有元素。这样可以防止出现多个数组,并使其代码结构更简洁,并且更易于维护和更新。
并不是说我简化了您的函数-一旦获得随机对象-您就可以使用对象属性来操纵其他元素。我还建议使用带有颜色的类,并添加或删除该类以实现CSS的颜色更改-添加类为元素着色比使用内联CSS更改更干净。
var quotes = [
{color: "#3b609b", quote: "First", author: "-First"},
{color: "#9b3b3b", quote: "Second", author: "-Second"},
{color: "#3b9b81", quote: "Third", author: "-Third"},
{color: "#7da5a4", quote: "Fourth", author: "-Fourth"}
];
$(document).ready(function() {
$('#clickMe').click(function(){
var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
$('#color').text('Color: ' + randomQuote.color);
$('#quote').text('Quote: ' + randomQuote.quote);
$('#author').text('Author: ' + randomQuote.author);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="clickMe">Click for a random quote</button>
<p id ="color"></p>
<p id ="quote"></p>
<p id ="author"></p>