[英]get all entries by column name: HTML table
I have a HTML table of the following format:- 我有一个以下格式的HTML表: -
+------+----------+----------+----------+
| name | subject1 | subject2 | subject3 |
+------+----------+----------+----------+
| xxx | pass | fail | pass |
| yyy | pass | pass | pass |
| zzz | pass | fail | fail |
+------+----------+----------+----------+
The table is dynamically created with json data obtained from the server. 使用从服务器获取的json数据动态创建该表。 I create every with name tag containing the names of the subject since the number of subjects are not constant.
我创建了每个包含主题名称的名称标签,因为主题的数量不是常数。 Now, what I want to do is have lists corresponding to subjects.. say subject1[],2 and so on and these lists will contain the list of pass/fails associated with that subject... I can then compute the number of pass/fails for that subjects and draw graphs.
现在,我想做的是拥有与主题相对应的列表..说subject1 [],2等等,这些列表将包含与该主题相关的通过/失败列表......然后我可以计算通过的数量/对于该主题失败并绘制图表。
While I am aware that this:can be used to get all rows for a particular column, 虽然我知道这个:可以用来获取特定列的所有行,
$('#mytable tbody td:nth-col(4)')
This wont be useful if the number of columns are fixed. 如果列数是固定的,这将不会有用。 Kindly let me know how to accomplish this using jquery/JS.
请告诉我如何使用jquery / JS完成此任务。 EDIT: data.json:-(if parsing can be done)
编辑: data.json :-(如果可以解析)
{"students": [{"student": John, "status": "pass", "subject": "english"},{"student": Joe, "status": "pass", "subject": "english"},{"student": Jill, "status": "fail", "subject": "french"}]}
I create every with name tag containing the names of the subject
我创建了包含主题名称的名称标签
As you're mentioning the name tag in all the elements you create, you can use the following selector: 当您在创建的所有元素中提及名称标记时,可以使用以下选择器:
$("[name='subject1']")
This will return you all elements which contains subject1 in its name attribute. 这将返回在其name属性中包含subject1的所有元素。
Instead of name
attribute, if you use data-subject
and store the subject name in that particular cell, then 如果您使用
data-subject
并将主题名称存储在该特定单元格中,则代替name
属性
$("[data-subject='subject1']")
This will return you all cells containing subject1. 这将返回包含subject1的所有单元格。
As discussed in the comments, it will be much easier to aggregate the data from the original source (which is a JavaScript object in this case) rather than extracting it from its visual representation (the DOM in this case). 正如评论中所讨论的,从原始源(在这种情况下是一个JavaScript对象)聚合数据要容易得多,而不是从其可视化表示(在这种情况下为DOM)中提取数据。
To group the data based on the subject
of each student data: 根据每个学生数据的
subject
对数据进行分组:
var res = {};
for (var i in data.students)
{
var item = data.students[i];
var subject = item.subject;
if (!res[subject])
res[subject] = { passedCount: 0, failedCount: 0 };
if (item.status == 'pass')
res[subject].passedCount++;
else
res[subject].failedCount++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.