簡體   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