【发布时间】:2020-12-20 21:17:31
【问题描述】:
我在一个页面上有一堆内容,包括像下面这样的一些部分,但穿插在其他内容部分中。
<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);
}
我觉得我走错了路,但不知道如何回到正确的轨道上。任何人都可以帮忙吗?
我一直在试图弄清楚如何做到这一点,希望我能清楚地解释我想要做什么。
【问题讨论】:
-
一个问题,在您的情况下,在每个循环中,一个事实将附加到所有这些事实 div 中,这是您想要的吗?
-
是的,每个事实 div 中有一个事实!
-
不明白,您是想找到如何附加或如何将文本放入所有 p 元素中?抱歉不明白你的问题
-
我正在尝试将 randomSpiderFacts 数组中的一项添加到每个事实 div。 IE。 randomSpiderFacts[1] 将进入第一个事实 div,randomSpiderFacts[2] 将进入第二个事实 div,randomSpiderFacts[3] 将进入第三个 div,依此类推。
标签: javascript jquery html arrays underscore.js