首页 > 解决方案 > 将数组中的一项附加到一个 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);

我想在页面上的p每个元素上附加一个包含一个随机事实的元素section.content-fact > div.container,但我一直坚持如何做到这一点。

到目前为止,我已经...

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

我觉得我走错了路,但不知道如何回到正确的轨道上。任何人都可以帮忙吗?

我一直试图弄清楚如何做到这一点,并希望我能清楚地解释我想要做什么。

标签: javascriptjqueryhtmlarraysunderscore.js

解决方案


您的代码很干净 expet appendChild() 函数,这不是 jquery 的一部分

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

见下面的片段:

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>


推荐阅读