首页 > 解决方案 > 如何添加标签 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);
  
}```




 

标签: javascript

解决方案


推荐阅读