简体   繁体   English

在 javascript 中的表中计数特定值

[英]Count specific value in table in javascript

I'm newbie and having a trouble on how can I count the number of value 1 and value 2 under the header 2 based on the image I attached.我是新手,我不知道如何根据我附加的图像计算 header 2 下的value 1value 2的数量。 So the result of value 1 should be 2 and the value 2 should also 2 Is there any trick how can I solve this, Im new with this,I hope anyone can help.所以value 1的结果应该是2value 2也应该是2有什么技巧可以解决这个问题,我是新手,希望有人能提供帮助。

在此处输入图像描述

This is what I tried my html这就是我尝试过的 html

 var tds = document.getElementById('table').getElementsByTagName('td'); var sum_paid= 0; var x = 0; for(var i = 0; i < tds.length; i ++) { if(tds[i].className == 'count_value"' && tds[i].innerHTML =="Value 2" ) { i++; } else if (tds[i].className == 'count_value"' && tds[i].innerHTML =="Value 1" ) { i++; } } console.log(x); console.log(i);
 <table id="table" name="table" id="table"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> </thead> <tbody> <tr> <td>Value 1</td> <td class="count_value">Value 1</td> <td>Value 1</td> </tr> <tr> <td>Value 1</td> <td class="count_value">Value 2</td> <td>Value 1</td> </tr> <tr> <td>Value 2</td> <td class="count_value">Value 1</td> <td>Value 1</td> </tr> <tr> <td>Value 2</td> <td class="count_value">Value 2</td> <td>Value 1</td> </tr> </tbody> </table>

Here's an option - just grab all elements with the class you have set on the second-column elements ( "count_value" ), and check if the text in those elements ( elem.innerText ) contains a "1" or "2" .这是一个选项 - 只需使用您在第二列元素( "count_value" )上设置的 class 获取所有元素,并检查这些元素( elem.innerText )中的文本是否包含"1""2"

 let elementsToCount = document.querySelectorAll('.count_value'); let numOne = 0, numTwo = 0; elementsToCount.forEach((elem) => { if (elem.innerText.includes('1')) numOne++; if (elem.innerText.includes('2')) numTwo++; }) console.log("Number one:", numOne); console.log("Number two:", numTwo);
 <table id="table" name="table" id="table"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> </thead> <tbody> <tr> <td>Value 1</td> <td class="count_value">Value 1</td> <td>Value 1</td> </tr> <tr> <td>Value 1</td> <td class="count_value">Value 2</td> <td>Value 1</td> </tr> <tr> <td>Value 2</td> <td class="count_value">Value 1</td> <td>Value 1</td> </tr> <tr> <td>Value 2</td> <td class="count_value">Value 2</td> <td>Value 1</td> </tr> </tbody> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM