gpt4 book ai didi

javascript - 从两个数组中选择随机项目并匹配项目顺序

转载 作者:行者123 更新时间:2023-12-01 04:06:20 26 4
gpt4 key购买 nike

只要单击 div,此代码就会以随机顺序在三个数组中进行洗牌。我想让两个数组“quotes”和“authors”显示相同的随机数组顺序。我希望“Third”等于“-Third”,“First”等于“-First”或当 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>

关于javascript - 从两个数组中选择随机项目并匹配项目顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com