首页 > 解决方案 > 遍历上述 JSFiddle 中的每个列表项并执行以下操作:

问题描述

[https://jsfiddle.net/gh/get/library/pure/gSchool/g67_fiddles/tree/master/dom-looping][1]

When you get to the page, press the "Run" button so that it correctly loads.
If the number inside the span is less than 5, add a class to the span of badge-danger
If the number inside the span is less than 10, add a class to the span of badge-secondary
Otherwise, add a class to the span of badge-danger

我的代码在下面,我不知道如何处理节点列表,也不知道循环它们的最有效方法并进行更改,例如在此示例中更改类。:

 document.addEventListener('DOMContentLoaded', function () {
      // Write your code here! Don't forget the above in later lessons.
      let lessThanFive = num => if (num < 5);
      lessThanTen = num => if (num < 10);
      let listItems = document.querySelectorAll('li');
      for (let i = 0; i < listItems.length; i++) {
        let spanNumbers = listItems[i].lastChild.lastChild;
        if (spanNumbers.filter(lessThanFive)) {
            // add class of "badge=danger"
        }
        else if (spanNumbers.filter(lessThanTen)) {
            //add class of "badge-secondary"
        } else {
            //add class of "badge=secondary"
         }
      }
    })
<ul>
  <li>Agile <span class="badge">15</span></li>
  <li>Command Line <span class="badge">2</span></li>
  <li>HTML <span class="badge">8</span></li>
  <li>CSS <span class="badge">7</span></li>
  <li>JavaScript <span class="badge">11</span></li>
</ul>

标签: javascripthtml

解决方案


这是一个简化版本:

循环通过徽章。在变量之前添加 + 会将其转换为数字。然后是一个基本的 if else 语句,结合添加一个类。

let badges = document.querySelectorAll('.badge');

badges.forEach(function(badge) {
  val = +badge.innerText;
  if(val < 5 || val > 10){
    badge.classList.add("badge-danger");
  }
  else{
     badge.classList.add("badge-secondary");
  }
})
.badge-secondary{color:green}
.badge-danger{color:red}
<ul>
  <li>Agile <span class="badge">15</span></li>
  <li>Command Line <span class="badge">2</span></li>
  <li>HTML <span class="badge">8</span></li>
  <li>CSS <span class="badge">7</span></li>
  <li>JavaScript <span class="badge">11</span></li>
</ul>

When you get to the page, press the "Run" button so that it correctly loads.
If the number inside the span is less than 5, add a class to the span of badge-danger
If the number inside the span is less than 10, add a class to the span of badge-secondary
Otherwise, add a class to the span of badge-danger


推荐阅读