所以我一直试图制作一个扩展程序,根据assignmentScores div中的一堆值来计算某人的平均成绩。这些成绩来自一个名为PowerSchool的网站,每个成绩都没有ID,所以我有jquery搜索页面。
这是页面格式化的方式,但这只是一个等级:
<div class="box-round" id="assignmentScores" style="">
<h2>Assignment Scores</h2>
<table border="0" cellpadding="0" cellspacing="0" align="center" width="99%">
<tbody><tr>
<th>Due Date</th>
<th>Category</th>
<th>Assignment</th>
<th>Standard</th>
<th class="center">Score</th>
<th class="center"></th>
<th class="center">Grd</th>
<th class="center" colspan="5">Codes</th>
</tr>
<tr class="oddRow">
<td>11/12/2015</td>
<td>Classwork</td>
<td>In Class Notes</td>
<td></td>
<td align="center">30/30</td>
<td align="center"></td>
<td align="center">A+</td>
这是我的代码:
$(document).ready(function() {
var arr = [];
var numerator = 0;
var denominator = 0;
i = 0;
//add value of all elements in assignmentScores that are centered to arr (grades are the only centered thing)
$('#assignmentScores').each(function()
if(isNaN($(this).attr('td [align="center"]')){
arr[i++] = $(this).attr('td [align="center"]');
}
);
//for every item in the array, add up numerators and denominators
for each(var item in numerator){
numerator += arr[item].substring(0, arr[item].indexOf("/")-1);
denominator += arr[item].substring(arr[item].indexOf("/")+1, arr[item].length);
}
//print out the grade in h1 of assignmentScores
$('#assignmentScores h1').append(numerator/denominator);
});
我对Javascript很陌生,我已经把它放在JSFiddle中了,我不确定它在做什么,或者它甚至做了什么。
感谢。
答案 0 :(得分:0)
是的,这是可能的,但它相当复杂。
相关的jQuery代码:
// We're going to do a lot of work, so let's get table in a variable
var table = $('#assignmentScores table');
// Which column is the score in? Find it here
var score_column = table.find('th:contains("Score")').index();
// Set up a regular expression for testing that the column contains something like '30/30'
var regex = /(\d+)\/(\d+)/;
// initialize the numerator and denomenator
var num = 0, den = 0;
// loop over all the table rows
table.find('tr').each(
function() {
// get the value from the column that is the "Score" column
var score = $(this).find('td:eq(' + score_column + ')').html();
// Run the regular expression to get the matches
var matches = regex.exec(score);
// If there are matches, add them to numerator and denomenator
if ($.isArray(matches) && typeof matches[2] != 'undefined') {
num+= +matches[1];
den+= +matches[2];
}
});
// Calculate the percent - but only if we actually have a numerator / denomenator
percent = (num && den) ? (num / den) * 100 : 0;
// And, for fun, append the values to the table
table.append('<tr><td colspan="' + score_column + '" style="text-align:right;">Total:</td><td>' + percent.toFixed(1) + '%</td></tr>');