繁体   English   中英

将数组中的一项附加到一个 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 来反转函数并使用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 EB 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM