我正在为电视节目写一个随机引用生成器,我的功能有些麻烦。我遇到的问题在于如何在包含引号的对象数组中选择对象的一部分。
randomNum变量可能也有问题,我不确定。 HTML是正确的 - 当我将randomQuote和randomAuthor的变量更改为它们显示的字符串时(但我必须删除数组以使其工作。不确定为什么会这样?)。
我希望有人可以帮助我。谢谢!
$(document).ready(function(){
function getQuote(){
var quotes = {
{idNumber: 1, author: "Frank", quote: "I love eggs, Charlie. And I love crabs. And I love boiling denim and banging whores. And I don't care if anyone doesn't like that about me, they don't have to stick around.",}
{idNumber: 2, author: "Mac", quote: "People change, Frank. Look at me: I went from a tiny twink to the muscle-bound freak you see before you.",}
{idNumber: 3, author: "Mac", quote: "Hey, warm sun, cool ocean breezes, getting rip shit on ham.",}
{idNumber: 4, author: "Mac", quote: "As a man who works very hard to maintain a certain level of physical excellence... I find shortcuts insulting.",}
{idNumber: 5, author: "Dennis", quote: "Dude do you have a boner right now?",}
}
var randomNum = Math.floor((Math.random()*quotes.length));
var randomQuote = "hey";
var randomAuthor = "oy";
$(".quote").text(randomQuote);
$(".author").text(randomAuthor);
}
$(".btn").on("click", function(){
getQuote();
});
});
答案 0 :(得分:0)
以下解决方案是否适合您?
var randomQuote = quotes[randomNum][quote];
var randomAuthor = quotes[randomNum][author];
答案 1 :(得分:0)
一些问题。您的引号变量必须是一个数组,每个元素需要用逗号分隔。否则,您可以使用quotes[randomNum]
访问数组的选定元素。请参阅以下代码以了解功能结果。
$(document).ready(function(){
function getQuote(){
var quotes = [
{idNumber: 1, author: "Frank", quote: "I love eggs, Charlie. And I love crabs. And I love boiling denim and banging whores. And I don't care if anyone doesn't like that about me, they don't have to stick around.",},
{idNumber: 2, author: "Mac", quote: "People change, Frank. Look at me: I went from a tiny twink to the muscle-bound freak you see before you.",},
{idNumber: 3, author: "Mac", quote: "Hey, warm sun, cool ocean breezes, getting rip shit on ham.",},
{idNumber: 4, author: "Mac", quote: "As a man who works very hard to maintain a certain level of physical excellence... I find shortcuts insulting.",},
{idNumber: 5, author: "Dennis", quote: "Dude do you have a boner right now?",}
]
var randomNum = Math.floor((Math.random()*quotes.length));
var randomQuote = quotes[randomNum].quote;
var randomAuthor = quotes[randomNum].author;
$(".quote").text(randomQuote);
$(".author").text(randomAuthor);
}
$(".btn").on("click", function(){
getQuote();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="quote"></p>
<p class="author"></p>
<a href="#" class="btn">Get Quote</a>