问题
如何选择使用特定属性(背景颜色 #00FF00)标识的文本节点值?
由于我是 javascript 新手,我不确定如何执行第一步:
- 使用 js dom 选择 00FF00 的节点
- 用“”作为分隔符分割字符串
- 循环并用 += 添加每个 split[2]
- 将总和 (240+80+600) 写入 html
代码
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var data = document.getElementsByTagName('span');
document.write(data);
};
</script>
</head>
<body>
<div class="box">
<span class="highlight">Dave collected 700 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 240 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 80 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 600 items.</span>
</div>
</body>
</html>
var els = document.querySelectorAll('span.highlight');
var len = els.length;
//console.log(len); //returns 4
var total = 0;
for (var i=0; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === 'rgb(0, 255, 0)') {
var txt = els[i].innerHTML;
//split txt into array
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);