随机报价选择器不会在彼此之后重复报价

时间:2018-05-06 09:41:03

标签: javascript html css

我正在尝试在Javascript中创建一个随机引用选择器,它不会相互重复相同的引用两次。我的问题是无法弄清楚如何不重复报价。

使用Javascript:

this

HTML:

function start() {
  var quotes = [];

  quotes.push({"content": "Quote #1", "cite": "—Cite #1"});
  quotes.push({"content": "Quote #2", "cite": "—Cite #2"});
  quotes.push({"content": "Quote #3”, "cite": "—Cite #3"});
  quotes.push({"content": "Quote #4", "cite": "—Cite #4"});
  quotes.push({"content": "Quote #5", "cite": "—Cite #5"});

  var randomNumber = Math.floor(Math.random() * quotes.length);

  $('#containerQuotes blockquote').text(quotes[randomNumber]['content'])
   .fadeIn(2000)
   .delay(2000)
   .fadeOut(2000, start);
  $('#containerQuotes cite').text(quotes[randomNumber]['cite'])
   .fadeIn(2000)
   .delay(2000)
   .fadeOut(2000, start);
} start();

CSS:

<div id="containerQuotes">
  <div class="fa fa-quote-left fa-2x"></div>
    <blockquote>Default Quote</blockquote><cite>Default Cite</cite>
</div>

有人有任何建议吗?如果有人知道实现这个的另一种方式,我会全力以赴。

谢谢你,
drujd3ka

(CSS格式现在有一些怪癖,但我想首先解决这个问题)

1 个答案:

答案 0 :(得分:0)

选择项目后,只需从数组中删除该项目:

const quotes = [
  {"content": "Quote #1", "cite": "—Cite #1"},
  {"content": "Quote #2", "cite": "—Cite #2"},
  {"content": "Quote #3", "cite": "—Cite #3"},
  {"content": "Quote #4", "cite": "—Cite #4"},
  {"content": "Quote #5", "cite": "—Cite #5"},
];
function start() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $('#containerQuotes blockquote').text(quotes[randomNumber]['content'])
   .fadeIn(2000)
   .delay(2000)
   .fadeOut(2000);
  $('#containerQuotes cite').text(quotes[randomNumber]['cite'])
   .fadeIn(2000)
   .delay(2000)
   .fadeOut(2000, start);
  quotes.splice(randomNumber, 1);
}
start();
#containerQuotes {
  bottom: 5px;
  text-align: center;
  left: 0px;
  margin-left: 600px;
  margin-right: 600px;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containerQuotes">
  <div class="fa fa-quote-left fa-2x"></div>
    <blockquote>Default Quote</blockquote><cite>Default Cite</cite>
</div>

请注意,您需要使用直引号而不是所谓的“智能引号”,否则您将收到语法错误。

此外,只需将start传递给fadeOut一个,否则其他start将在每次后续迭代中开始运行。