获取jQuery .click()多次激活

用户5931546

我在一个报价机上工作,单击该报价机会显示随机报价之一,并且它是作者在我的数组中找到的。我可以让它显示一次随机报价,但是再次单击该按钮则无济于事。

//VARIABLES
///////////////
var quotes = [
  ["Quote 1", "Author 1"],
  ["Quote 2", "Author 2"],
  ["Quote 3", "Author 3"],
  ["Quote 4", "Author 4"]
];

var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];


//FUNCTIONS
///////////////
function quoteGeneration() {
  $(".quotes").replaceWith(randomQuote);
};


//QUOTE BUTTON
/////////////////
$(".quote-button").click(function() {
  quoteGeneration();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quote-box">
  <h1>Random Quote Generator</h1>
  <p class="quotes">This is where the quotes go.</p>
  <span class="quote-authors">Quote author</span>

  <div class="social-media">
    <a href="#"><i class="fa fa-twitter"></i></a>
    <a href="#"><i class="fa fa-tumblr"></i></a>
  </div>

  <button class="quote-button">New Quote</button>
</div>

罗里·麦克罗森(Rory McCrossan)

有两个主要问题。首先是因为您.quotes在第一次单击时就从DOM中删除了该元素。使用text()代替replaceWith()

$(".quotes").text(randomQuote);

第二个原因是您的逻辑存在缺陷,因为您在页面加载时仅随机选择了一个引号。这应该在点击处理程序中完成。试试这个:

var quotes = [
  ["Quote 1", "Author 1"],
  ["Quote 2", "Author 2"],
  ["Quote 3", "Author 3"],
  ["Quote 4", "Author 4"]
];

$(".quote-button").click(function() {
  var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
  $(".quotes").text(randomQuote);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote-box">
  <h1>Random Quote Generator</h1>
  <p class="quotes">This is where the quotes go.</p>
  <span class="quote-authors">Quote author</span>

  <div class="social-media">
    <a href="#"><i class="fa fa-twitter"></i></a>
    <a href="#"><i class="fa fa-tumblr"></i></a>
  </div>

  <button class="quote-button">New Quote</button>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章