将HTML元素设置为随机对象键:值对

时间:2016-10-18 20:52:22

标签: javascript jquery html multidimensional-array

我正在尝试使用“数据库”来点击按钮时随机循环显示一些引号并将HTML中的现有引号更改为随机引用和现有作者的方式相同< / p>

var myDatabase = [
    {quote:"I have learned silence from the talkative...", author:"Khalil Gibran"}, 
    {quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
    {quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
 ];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');

$("#quoteButton").click(function() {
    var rand = Math.floor(Math.random()*database.length)
    newQuote = myDatabase.[rand].quote;
    newAuthor = myDatabase.[rand].author;
});

2 个答案:

答案 0 :(得分:1)

首先是你的数据库&#34;有语法错误。它应该是:

var myDatabase = [{
  "quote": "I have learned silence from the talkative...",
  "author": "Khalil Gibran"
}, {
  "quote": "One of the blessings of old friends that you can afford to be stupid with them.",
  "author": "Ralph Waldo Emmerson"
}, {
  "quote": "Once we accept our limits, we go beyond them.",
  "author": "Albert Einstein"
}];

其次,你将vanilla JS与Jquery混合在一起。虽然这在技术上并不是错误的,但如果你只是坚持一个或另一个,它会更容易阅读

var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');

最后,click方法中的语法不正确。您为newQuote和newAuthor变量赋值,而不是操纵元素。您要做的是使用.text()方法将对象值添加到DOM。

此外,您不需要在[rand]整数之前使用点符号,并且您希望myDatabase.length不是database.length

$("#quoteButton").click(function() {
    var rand = Math.floor(Math.random() * myDatabase.length)
    newQuote.text(myDatabase[rand].quote) 
    newAuthor.text(myDatabase[rand].author)
});

以下是一个工作示例:https://codepen.io/mark_c/pen/pExxQA

答案 1 :(得分:-1)

那样的东西?

var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"}, 
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
 ];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');

$("#quoteButton").click(function() {
    var rand = Math.floor(Math.random()*database.length)
    $(newQuote).text(myDatabase[rand].quote);
    $(newAuthor).text(myDatabase[rand].author);
});