首页 > 解决方案 > jQuery:有时随机失败

问题描述

我有一个博客,在每篇文章的底部随机宣传 x3 篇文章。有时,此功能无法显示全部 3 个(缺少 1 个)。

我看不出问题出在哪里。

jQuery

$.get("https://www.citychurchchristchurch.co.nz/blog.php", function(data) {
    var $quotes = $(data).find(".container-articles-5"),
      count = $quotes.length,
      $random = function() {
        return $quotes.eq(Math.floor(Math.random() * count));
      };
    $(".blog-ad-1").append($random);
});

HTML(显示广告的地方)

<aside class="blog-ad-4">
    <div class="blog-ad-5">
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
      <div class="blog-ad-3">
        <div class="blog-ad-1"></div>
      </div>
    </div>
</aside>

应显示所有 3 个广告。在此处查看现场演示(靠近底部):https ://www.citychurchchristchurch.co.nz/blog/eo-cycling-20181030

标签: jqueryhtmlrandom

解决方案


这只是一个猜测,但我会尝试以下方法:

$.get("https://www.citychurchchristchurch.co.nz/blog.php", function(data) {
  var $quotes = $(data).find(".container-articles-5"),
  count = $quotes.length,
  $random = function() {
    var articleNumber = Math.floor(Math.random() * count);
    console.log(articleNumber);
    return $quotes.eq(articleNumber);
  }
  $(".blog-ad-1").append($random);
});

通过这种方式,您可以检查是否总是在生成的同一 articleNumber(例如 0)上显示广告失败。


推荐阅读