javascript - 对多个元素重复脚本

标签 javascript jquery html

嘿,我有这个代码:

<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;
});

注意: querySelectorquerySelectorAll使用 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/

相关文章:

javascript - 让 Jquery 记住 attr() 和数据

javascript - 遍历元素以查找特定 ID

jquery - 使用 jQuery Mobile 的 not 选择器

javascript - 搜索 3D 照片库(HTML5 或 Flash)

java - JSF2.0 中的 session 无效

javascript - 如何将项目添加到列表?

javascript - 我应该如何对这个简单的 javascript 动画进行逆向工程?

jquery - 父元素在其被子元素覆盖的部分变得透明。可能的?

html - Bootstrap 中的卡片不显示边框(Bootstrap 3.4.0)

php - 为什么 CSS 不将内容从 php echo 输出移动到 html?