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



我正试图使用我所做的"数据库"来循环一些引号随机当按钮被点击,并改变现有的引用在HTML中的随机引用和现有的作者在相同的方式

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;
});

首先你的"数据库"有语法错误。它应该是:

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"
}];

其次,你把JS和Jquery混在一起了。虽然这在技术上没有错,但如果你只坚持使用其中一个

,则更容易阅读。
var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');

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

另外,您不需要在[rand]整数之前使用点表示法,并且希望使用myDatabase。长度不是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

是这样吗?

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);
});

相关内容

  • 没有找到相关文章

最新更新