将数组中的一项附加到一项 div

Append one item from an array to one div

我在一个页面上有一堆内容,包括下面的一些部分,但穿插在其他内容部分中。

<main>
  <section class="module content content-fact">
    <div class="container" id="0"></div>
  </section>

  <section class="module content content-fact">
    <div class="container" id="1"></div>
  </section>

  <section class="module content content-fact">
    <div class="container"></div>
  </section>
</main>

我有一组使用 Underscore.js --> _.shuffle() 函数随机化的随机事实。

const spiderFacts = [
    "Spiders are not insects. They are arachnids. Both arachnids and insects are arthropods.",
    "Spiders eat about 200 kilograms of insects per hectare per year.",
    "Spiders inhabit just about every corner of the globe.",
    "Charlotte in E.B. White’s Charlotte’s Web was a barn orbweaver spider, <em>Araneus cavaticus<em>."
]

const randomSpiderFacts = _.shuffle(spiderFacts);

我想向页面上的每个 section.content-fact > div.container 添加一个包含一个随机事实的 p 元素,但我不知道如何做到这一点。

到目前为止我已经...

for (var fact in randomSpiderFacts) {
  var newElement = document.createElement('p');
  newElement.className = "fact";
  newElement.innerHTML = randomSpiderFacts[fact];
  $('.content-fact > .container').appendChild(newElement);
}

我觉得我的做法是错误的,但我不确定如何回到正确的轨道上。谁能帮忙?

我一直在努力弄清楚如何做到这一点,希望我能清楚地解释我想做的事情。

您的代码在 appendChild() 函数之外是干净的,这不是 jquery

的一部分

此外,每个事实都将附加到每个 .fact div ,因此通过循环 div 来反转函数,并使用 [=] 将事实内容附加到每个 div 12=]

请参阅以下代码段:

const spiderFacts = [
    "Spiders are not insects. They are arachnids. Both arachnids and insects are arthropods.",
    "Spiders eat about 200 kilograms of insects per hectare per year.",
    "Spiders inhabit just about every corner of the globe.",
    "Charlotte in E.B. White’s Charlotte’s Web was a barn orbweaver spider, <em>Araneus cavaticus<em>."
]

const randomSpiderFacts = _.shuffle(spiderFacts);

$('.content-fact > .container').each(function(i,el){
  // check if not exceeding the array so return empty string
  var factContent = randomSpiderFacts[i] ? randomSpiderFacts[i] : "";
  $("<p>").addClass("fact").html(factContent).appendTo(el);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.0/underscore-min.js"></script>

<section class="module content content-fact">
  <div class="container" id="0"></div>
</section>

<section class="module content content-fact">
  <div class="container" id="1"></div>
</section>

<section class="module content content-fact">
  <div class="container"></div>
</section>