嘿,我有这个代码:
<body>
<table>
<tr>
<td class="first">100</td>
</tr>
</table>
<h4 class=curs style="display:none">10</h4>
<script>
document.body.onload = function(){
var firstTdVal = document.getElementsByClassName('first')[0].innerHTML;
var secondTdVal = document.getElementsByClassName('curs')[0].innerHTML;
var valueToBeShown = parseInt(firstTdVal)/ parseInt(secondTdVal);
document.getElementsByClassName('first')[0].innerHTML = valueToBeShown ;
}
</script>
</body>
正如你所看到的“.first”中有一个数字,这个数字被划分为“.curs”,结果也显示在“.first”中。现在的问题是,例如我添加了 100 个 td表中的类“.第二,.第三...,.百”。如何使脚本对所有 td 执行与“.first”相同的操作(划分为“.curs”)。我该怎么做在我的 JS 中,通过保持复杂性来实现这一点。
最佳答案
使用document.querySelectorAll
获取匹配元素的数组(与 CSS 选择器匹配),然后使用 forEach
循环它们,应用逻辑一td
一次。像这样:
// querySelector gets the first element matched. textContent get the text of that element
var cursValue = parseInt(document.querySelector(".curs").textContent);
// querySelectorAll get an array of all the matched elements
var tds = document.querySelectorAll("td");
// loop through that array one td at a time
tds.forEach(function(td){
// get the text of the current td
var value = parseInt(td.textContent);
// if the value is not valid (a string for example) return and don't process anymore for this td (go straight to the next one).
if(isNaN(value)) return;
// calculate the new value
value = value / cursValue;
// change the text of this td (update it to the new value)
td.textContent = value;
});
注意: querySelector
和querySelectorAll
使用 CSS selectors 匹配元素,因此要使用类匹配元素,选择器应该是 ".className"
,使用 ID 进行匹配:"#someID"
, ... 所有 CSS 选择器都被接受(即使是这个: "#anID>li.some-class a:not([href])"
)。
注2: tds
是一个数组,所以如果你不想使用 forEach
你可以使用普通的for
循环(for(var i = 0; i < tds.length; i++) ...
)。
关于javascript - 对多个元素重复脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41915977/