【问题标题】:Set HTML elements to random object key:value pairs将 HTML 元素设置为随机对象键:值对
【发布时间】:2017-02-28 07:05:40
【问题描述】:

我正在尝试使用“数据库”在单击按钮时随机循环浏览一些引号,并以相同的方式将 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;
});

【问题讨论】:

  • 您有问题吗?
  • 我们能得到更多关于这个的信息吗?
  • 不确定这是否是您的问题,但请不要使用方括号从数组中按索引获取项目,无需使用点分隔符 - 它应该是 myDatabase[rand].quote,不是myDatabase.[rand].quote

标签: javascript jquery html multidimensional-array


【解决方案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"
}];

其次,您将香草 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

【讨论】:

  • OP 定义 myDatabase JavaScript 对象数组的语法没有错。您的修改仅在声称是 JSON 的字符串中引用了对象文字不需要的属性名称。其余的答案都非常正确且解释清楚。
  • @MikeMcCaughan - 更正了属性声明,但由于第二个和第三个对象中缺少逗号,因此存在语法错误。
【解决方案2】:

类似的东西?

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

【讨论】:

  • 欢迎来到 Stack Overflow!请注意,您的代码和mark_c's 之间没有显着差异。但是,该答案包括对 OP 代码有什么问题以及他为修复它做了什么的详细解释。在您继续回答问题时要记住一些事情。
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多