【问题标题】:How to solve Uncaught TypeError: Cannot read property '0' of undefined for random quote generator?如何解决 Uncaught TypeError: Cannot read property '0' of undefined for random quote generator?
【发布时间】:2020-10-29 11:28:17
【问题描述】:

我有一个 jQuery 代码的随机报价生成器 sn-p,它给了我以下控制台错误:

当我单击按钮时,它会成功显示第一个引号,但随后停止。

这是我的代码:

jQuery(document).ready(function(){
      jQuery("#change").click(function(){
var quotes = [
  ["It Crowd" ],
  ["Black Books"],
  ["Still Game"],
  ["quote 4"],
];
  // generate random integer< array.length
var number = Math.floor(Math.random()* (quotes.length+1));
//get the elements or just put them in the document write below
var showQuotes = quotes[number][0];
        
  //                      
  jQuery("#quotecontent").fadeOut("medium",function(){
           var newer = jQuery(
             '<div id="content"><p id="quote">'  + showQuotes + '</p></div>' ); 
        jQuery(this).replaceWith(newer);
      jQuery('#quotecontent').fadeIn("medium");
      });                          
      });    
});

这里是 HTML

<div id="quotecontent">
<p id="quote">This is the original quote</p>
</div>
 <div id="btn-container">
<button id="change">Press</button>
      </div>

这是错误信息:

未捕获的类型错误:无法读取未定义的属性“0”

我知道这与这部分代码有关:

var showQuotes = quotes[number][0];

但我只是不确定为什么它不起作用,因为我对数组有点陌生。如果有人可以帮助我理解为什么这不起作用,那将不胜感激!!!

Codepen 如果有帮助:https://codepen.io/kiaramelissa/pen/XWXqgVa

【问题讨论】:

  • quotes 的随机索引是 Math.floor(Math.random() * quotes.length),而不是 Math.floor(Math.random() * (quotes.length + 1))
  • 这能回答你的问题吗? Getting a random value from a JavaScript array
  • 感谢您的回复,但不...我用这个 sn-p 更新了 CodePen,但它仍然无法正常工作。我也尝试阅读该线程,但没有任何效果?
  • 您将&lt;div id="quotecontent"&gt; 替换为&lt;div id="content"&gt;,这样jQuery 就再也找不到您的元素了。
  • 您的 Codepen 代码在 Chrome 上运行良好。不确定您在哪个浏览器上检查。如果您提及客户端问题时使用的浏览器,它总是有帮助的。我想补充的另一点是“引号”是一个数组数组,在这种情况下不是必需的。除非您想为每个报价存储更多详细信息,否则您可以简单地使用 var quotes = ["It Crowd", "Black Books", "Still Game","quote 4"];var showQuotes = quotes[number];

标签: jquery arrays random


【解决方案1】:

尝试删除此行的 [0]:

var showQuotes = quotes[number][0];

quotes[number] 将返回存储在该位置的字符串。使用那个 [0] 你将永远找不到任何东西,因为引号 [number] 它是最终值而不是数组。

编辑:

变化:

var quotes = [
 ["It Crowd" ],
 ["Black Books"],
 ["Still Game"],
 ["quote 4"],
];

收件人:

var quotes = [
  "It Crowd",
  "Black Books",
  "Still Game",
  "quote 4"
];

【讨论】:

  • 感谢您的回复,但这样做我仍然遇到同样的问题
猜你喜欢
  • 2017-04-24
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 2019-01-21
  • 2019-02-12
  • 2015-07-29
相关资源
最近更新 更多