2016-02-14 3 views
-1

Таким образом, я пытаюсь сделать расширение, которое вычисляет средний класс чей-то, основанный на связке значений в divs assignScores. Оценки приходят с веб-сайта под названием PowerSchool, и для каждого отдельного класса нет идентификатора, поэтому я ищу jquery на странице.Javascript вычисляет оценки со страницы

Это способ форматирования страницы, но это только один класс:

<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, и я ve положил его в JSFiddle, и я не уверен, что он делает, или если он даже делает что-то.

Спасибо.

+0

Что вы хотите сделать? Каким должен быть результат? и в чем проблема? – nAviD

+0

пытается сделать javascript-программу, которая получает оценку вокруг «/» в центрированном div и будет вычислять среднее значение всех числителей и знаменателей, для этого примера результат должен быть 100%, а проблема заключается в том, Делать что-нибудь. Спасибо за ответ. – kyleai

+0

У вас есть ссылка на Fiddle? –

ответ

0

Да, это возможно, но это довольно сложно.

Here's a working Fiddle

Соответствующий 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>'); 
+0

Большое вам спасибо, это потрясающе – kyleai

+0

Привет, еще раз спасибо за это. Когда в числителе есть десятичные числа, он принимает цифры только после «.». Я отредактировал его так, чтобы это регулярное выражение, так что у него будет необязательный период между 1 + цифрой и 0 + цифрами. var regex = /(\d+\.?\d*)\/(\d+)/; – kyleai

Смежные вопросы