javascript - 遍历上述 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>
解决方案
这是一个简化版本:
循环通过徽章。在变量之前添加 + 会将其转换为数字。然后是一个基本的 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
推荐阅读
- apache-spark - 用于预测的 Spark 中的 PMML 执行
- ssh - Plotly 和 JupyterLab:图表未从远程服务器显示
- java - 构造函数和实例变量之间的区别
- php - 如何更有效地比较大海捞针
- prolog - 优化 clp(FD) 标记
- asp.net-core - Kestrel HTTPS 重定向导致没有响应,调试日志“应用程序在未读取整个请求正文的情况下完成”。
- python-3.x - Python:写入文件变音符号作为转义字符序列
- assembly - 汇编语言中的结构
- ios - 更新到最新版本的 Visual Studio 和 Xamarin 后无法启动应用程序
- sql - SQL:将 table1 和 table2 与合并的行链接,然后链接到 table3