javascript - 如何添加标签 JS
问题描述
我正在尝试添加应该由 JS 生成的标签。不幸的是,它仍然无法正常工作。我看到使用 console.log 链接已生成但未显示在页面上。
<section class="posts">
<article class="post active" id="article-1" data-tags="cat cactus scissors">
<h3 class="post-title">Article 1</h3>
<p class="post-author">by Marion Berry</p>
<div class="post-content">
<p>Duis non dolor efficitur erat interdum fringilla a lobortis dolor. Aenean in massa
viverra, pretium augue et, imperdiet diam. Proin varius vitae lectus ut suscipit. Etiam
metus lacus, molestie at ante eget, gravida tristique metus. Morbi finibus elit mi, ut
aliquam libero tempor eu.</p>
<p>Curabitur a arcu ut nunc ornare tempor. Vestibulum et augue purus. Sed mattis auctor
iaculis. Duis placerat tempus nisl, et commodo sem varius sed. Ut ac ultrices leo.
Aliquam efficitur augue a scelerisque lacinia. Donec sit amet justo lacus.</p>
<p> Duis tincidunt tellus non lorem molestie lobortis. Ut nec mauris consectetur, convallis
nisl vel, venenatis magna.Sed efficitur egestas purus, eu fermentum leo sodales in.</p>
</div>
<div class="post-tags">
<p><strong>Tags:</strong></p>
<ul class="list list-horizontal">
</ul>
</div>
</article>
generateTags 函数计划:查找所有文章
开始循环:每篇文章
查找标签包装器
make html variable with empty string
get tags from data-tags attribute
split tags into array
START LOOP: for each tag
generate HTML of the link
add generated code to html variable
END LOOP: for each tag
insert HTML of all the links into the tags wrapper
END LOOP:对于每篇文章
下面是javasript代码:
function generateTags(){
const optArticleTagsSelector='.post-tags .list';
const optArticleSelector = '.post';
const articles = document.querySelectorAll(optArticleSelector);
for (let article of articles) {
const TagsWrapper = article.querySelectorAll(optArticleTagsSelector);
TagsWrapper.innerHTML='';
let html = '';
const articleTags = article.getAttribute('data-tags');
const articleTagsArray = articleTags.split(' ');
for (let tag of articleTagsArray){
const HTMLlink = '<li><a href="#tag-' + tag + '"><span>'+ tag +'</span></a></li>';
html=html + HTMLlink;
}
/* insert HTML of all the links into the tags wrapper */
TagsWrapper.innerHTML=html;
console.log(TagsWrapper);
}```
解决方案
推荐阅读
- ros - 当给定导航目标时,胡椒会原地旋转
- hive - Hive 中以秒为单位的日期差异不正确
- windows - Windows App 版本:认证完成后可以取消(发布手册)
- python - 在python中交换大小写的脚本
- javascript - 如何使用 justifyContent 和 alignItems 与 contentContainerStyle 等反应原生平面列表
- react-native - Google 地图未使用新的 API 密钥加载
- reactjs - 位跟踪 React 组件的全局上下文
- html - 使用 moment.js 来指示 mongoDB/mongoose 上次更新的时间?
- notepad++ - 如何用记事本++中的一个共同点替换所有单词
- javascript - 如何使用 javaScript 文件作为其他 JavaScript 文件的高阶包装器