javascript - 将数组中的一项附加到一个 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);
}
我觉得我走错了路,但不知道如何回到正确的轨道上。任何人都可以帮忙吗?
我一直试图弄清楚如何做到这一点,并希望我能清楚地解释我想要做什么。
解决方案
您的代码很干净 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>
推荐阅读
- javascript - 使用 JavaScript/JQuery 过滤 HTTP 请求
- quantlib - QuantLib (Python) ZeroCouponBond。适当的收益率曲线
- java - JavaFX - 通过按钮编辑树视图节点文本
- mysql - 为什么我从这个 SQL 查询中得到错误的结果?
- java - 计算模型照明的法线导致模型不再渲染
- apache-spark - 2个火花应用程序不能使用相同的组ID从相同的Kafka主题并行消费
- xslt - 将 XSLT 中的字母数字与破折号组合
- xamarin - 如何通过默认系统 pdf 应用程序中的 FileProvider 在 Xamarin.Android 中打开内部创建的 pdf?
- c - 使用带有 openssl 的 libc 时修复动态链接器错误
- excel - ActiveSheet.PasteSpecial Paste:=xlPasteValues 不起作用