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

时间:2018-05-03 19:04:10

标签: javascript jquery html arrays underscore.js

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

<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);
}

我觉得我的方式不对,但我不确定如何回到正轨。有人可以帮忙吗?

我一直试图弄清楚如何做到这一点,并希望我解释了我想要做的事情。

1 个答案:

答案 0 :(得分:2)

你的代码是干净的,使用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 exceeeding 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>