【问题标题】:Generating random number from range on click, that isn't the same as previous numbers单击时从范围生成随机数,与以前的数字不同
【发布时间】:2022-02-01 21:50:44
【问题描述】:

我真的不知道自己在做什么,但一直在玩 jQuery 来实现这一点。除了偶尔连续两次显示相同的推荐之外,我的功能运行良好,这是我试图解决的问题。这是我尝试的无法计算的代码,我很确定这是我不理解的明显内容!任何帮助表示赞赏。

您可以在推荐页脚中看到预期的功能:https://blue-coast-f4d2bc.webflow.io/contact

     function getNumber(previous) {
  if (previous === undefined) {
      i = Math.floor(Math.random() * 14) + 1;
      return i;
  }
  else {
    while {
      i = previous; 
      i = Math.floor(Math.random() * 14) + 1;
    }
    return i;
  }


var quoteNumb = getNumber();
 $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').addClass('show');
  
  var footHeight = $('.testimonial-container').height();
$('.testimonial-container').css({'min-height': footHeight  + 'px'});
  $('.testimonial-container').css({'max-height': footHeight  + 'px'});
  
 $(document).ready(function() {
            $(".refresh-button").click(function() {
                $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeOut(1000, function() {
                $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').removeClass('show');
                  quoteNumb = getNumber(quoteNumb);
                $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').addClass('show');
                $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeIn(1000);
                });
            });
        });

【问题讨论】:

  • 这个while { i = previous; i = Math.floor(Math.random() * 14) + 1; } 没有意义。我猜您打算比较 i == previous 并将其作为 while 循环的条件。此外,getNumber() 在您的代码中只被调用一次,并且没有 previous 参数。
  • 目的是在单击刷新按钮时生成一个新数字,该数字与前一个数字不同。因此,只要 i==previous 这个条件不满足,我必须从 14 的列表中再次生成一个新数字。尽管我不断破坏代码,但无法弄清楚如何实现它。
  • do { i = Math.floor(Math.random() * 14) + 1; } while (i === previous);
  • 好极了,似乎奏效了!非常感谢:)

标签: javascript jquery css variables random


【解决方案1】:
   let quotes = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

let state = 0;

let sequence = getRandomSequence(0, quotes.length);

function getRandomSequence(start, length) {
    return shuffle(generateRange(start, length))
}
  
function generateRange(start, length) {
    return Array.from({ length }, (v,k) => k + start)
}
  
// Fisher-Yates shuffle
function shuffle(arr) {
    arr = [...arr];
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

function nextInSequence() {
    let quoteNumb = quotes[sequence[(state++) % sequence.length]];
    $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').addClass('show');
          $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeIn(1000);
}

nextInSequence();

$(document).ready(function() {
            $(".refresh-button").click(function() {
        $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeOut(1000, function() {
                $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').removeClass('show');
                  nextInSequence();
                });
            });
        });

【讨论】:

  • 不错的答案亚当 :-)
【解决方案2】:

我建议创建一个随机序列来确定推荐出现的顺序。这样在所有项目出现之前它们不会重复。

我们首先创建一个像 0,1,2,3,4 ... N 这样的序列,然后我们使用(在这种情况下)Fisher-Yates 类型随机播放它。

一旦我们创建了序列,获取下一个项目就很容易了。在这个例子中,我们循环遍历所有项目,然后返回开始。

let state = 0;

let sequence = getRandomSequence(1, 6);

function getRandomSequence(start, length) {
    return shuffle(generateRange(start, length))
}
  
function generateRange(start, length) {
    return Array.from({ length }, (v,k) => k + start)
}
  
// Fisher-Yates shuffle
function shuffle(arr) {
    arr = [...arr];
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

// Should drop in as a replacement...
function getNumber() {
    return sequence[(state++) % sequence.length];
}

quoteNumb = getNumber();

function showNextQuote() {
    $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeOut(1000, function() {
        $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').removeClass('show');
        quoteNumb = getNumber(quoteNumb);
        $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').addClass('show');
        $('.footer-testimonial-quote:nth-of-type('+quoteNumb+')').fadeIn(1000);
    });
}

showNextQuote();
.footer-testimonial-quote
{ 
    visibility: hidden;
}

.show 
{ 
    visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<button onclick='showNextQuote()'>
Next quote
</button>
<br><br>

  <div class="footer-testimonial-quote">What a great product!</div>
  <div class="footer-testimonial-quote">Great product!</div>
  <div class="footer-testimonial-quote">Love it</div>
  <div class="footer-testimonial-quote">Amazing</div>
  <div class="footer-testimonial-quote">Meh</div>
  <div class="footer-testimonial-quote">Awesome, would recommend</div>

【讨论】:

  • 我真的很喜欢这个想法,但是对于我的应用程序,推荐书存储为 CMS 项目,显示在所有项目的列表中,然后基于使用 javascript 添加 .show 类显示。我尝试使您的代码适应以下目的,但没有用......有什么想法吗?
  • 我实际上会更新为使用 getNumber() 函数,就像在您的原始示例中一样。这应该很容易适应您的代码!
  • 我已更新以显示列表中的第 n 个元素..
  • 工作就像一个魅力,非常感谢特里我感谢你抽出时间来做这件事! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2010-12-24
  • 2015-01-11
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多