【发布时间】: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))。 -
感谢您的回复,但不...我用这个 sn-p 更新了 CodePen,但它仍然无法正常工作。我也尝试阅读该线程,但没有任何效果?
-
您将
<div id="quotecontent">替换为<div id="content">,这样jQuery 就再也找不到您的元素了。 -
您的 Codepen 代码在 Chrome 上运行良好。不确定您在哪个浏览器上检查。如果您提及客户端问题时使用的浏览器,它总是有帮助的。我想补充的另一点是“引号”是一个数组数组,在这种情况下不是必需的。除非您想为每个报价存储更多详细信息,否则您可以简单地使用
var quotes = ["It Crowd", "Black Books", "Still Game","quote 4"];和var showQuotes = quotes[number];