Доля в процентах в таблице HTML с помощью jQuery (новая строка) - PullRequest
0 голосов
/ 26 апреля 2018

У меня была таблица, и мне удалось ее транспонировать, а затем добавить классы и идентификаторы в определенные HTML-теги (например, в таблицу). Затем я преобразовал числа (с запятой) в целое число. Сейчас я пытаюсь рассчитать процентную долю и представить ее в новой строке.

Итак, это таблица: enter image description here

Я пытаюсь добавить следующую строку: enter image description here

где процент рассчитывается для двух ячеек. (например, 7262/9985 * 100 и 2723/9985 * 100).

По какой-то причине я вижу что-то в Jsfiddle, где во фрагменте я не получаю результатов (связанный с jQuery ??). https://jsfiddle.net/Templates/0002wsuq/

Во-первых, можно ли объединить две функции (проверить фрагмент или JSfiddle) в одну? Во-вторых, как я могу добавить это в новый ряд?

//Add Class to Table (Total Column)
$(document).ready(function () {
    $('table tr:nth-child(2) td:nth-child(4)').addClass('Total');
});

//Add Class to Table (Second Row)
$(document).ready(function () {
    $('table tr:nth-child(2) td:nth-child(2), table tr:nth-child(2) td:nth-child(3)').addClass('Share');
});

//Add Id to Table 
$(document).ready(function () {
    $('table').attr('id', 'table_result');
});

//Calculate Percentage Change
var total_per = 0;
var totalNumber = 0;
var totalNumber2 = 0;
var cellNumber = 0;

//Get total number of cells
$.each($('#table_result td.Share'), function() {
  if (!isNaN($(this).text())) 
  {
    totalNumber2 = totalNumber2 + parseInt($(this).text().split(",").join(""));
  }
	
  return totalNumber2;

});


$.each($('#table_result td.Share'), function() {
  if (!isNaN($(this).text())) 
  {
    cellNumber = ((parseInt($(this).text().split(",").join(""))/totalNumber2)*100).toFixed(2) ;
    
    $('<td><span></span></td>')
     .text( cellNumber + '%' ).appendTo(this);
  }

});
@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Roboto');

*{
  font-family: 'Roboto', sans-serif;
  text-transform:capitalize;
  overflow:hidden;
  margin: 0 auto;
  text-align:left;
}

table {
	color:#666;
	font-size:12px;
	background:#e13195;
	border:#ccc 1px solid;
	-moz-border-radius:3px;
	-webkit-border-radius:3px;
	border-radius:3px;
  border-collapse: collapse;
  width: 100%;
}

table td {
	padding:10px;
	border-top: 1px solid #ffffff;
	border-bottom:1px solid #e0e0e0;
	border-left: 1px solid #e0e0e0;
	background: #fafafa;
	background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
	background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
  width: 6.9in;
}

table tbody tr:first-child td
{
	background: #e13195!important;
  color:#fff;
}

table tbody tr th
{
  padding:10px;
  border-left: 1px solid #e0e0e0;
	background: #e13195!important;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<table><tbody><tr><td>Ddddddddd</td><td>Ccccccccc</td><td>Bbbbbbbbb</td><td>Total</td></tr><tr><td>Aaaaaaaaa</td><td>7262</td><td>2723</td><td>9985</td></tr><tr><td>Rate</td><td>56</td><td>55</td><td>56</td></tr></tbody></table>

1 Ответ

0 голосов
/ 30 апреля 2018

Я нашел решение, которое вставлено ниже. Я также заставил это работать для числа X чисел (tds). Процентная доля рассчитывается для первой метрики, которая составляет Aaaaaaaaa .

//Calculate how many dimension values we have  (transposed in the header which is a td in this case) --> We need that to find the tds and assign the "total" and "share" classes 
tdCount = $("tr:first td").length;

//Create the string that points to the Total td
stringTotaltd = 'table tr:nth-child(2) td:nth-child(' + tdCount + ')';

//Create the string that points to the Share tds
var stringTotaltdShare = '';

for (i = 2; i < tdCount; i++) {  //i has to start from 2 as the first column has the metric names
	stringTotaltdShare += 'table tr:nth-child(2) td:nth-child(' + i + '),';
}


//Remove the comma in the end
stringTotaltdShare = stringTotaltdShare.slice(0,-1);

//Add Class to Table (Total Column)
$(stringTotaltd).addClass('Total');

//Add Class to Table (Second Row)
$(stringTotaltdShare).addClass('Share');

//Add Id to Table 
$('table').attr('id', 'table_result');

//Calculate Percentage Change

var total_per = 0;
var totalNumber = 0;
var totalNumber2 = 0;
var cellNumber = 0;

//Get total number of cells
$.each($('#table_result td.Share'), function() {

	metric = parseInt($(this).text().split(",").join(""));
   
  if (!isNaN(metric)) 
  {
    totalNumber2 = totalNumber2 + metric;
  }
	
  return totalNumber2;

});

//Additional row for the percentage share


$("#table_result tbody tr:nth-last-child(2)").after('<tr id="percentage"></tr>');
$('<td></td>')
   .text('Percentage Share %').appendTo('#percentage');

$.each($('#table_result td.Share'), function() {
	metric = parseInt($(this).text().split(",").join(""));

	//Check whether metric value is a number
  if (!isNaN(metric)) 
  {
    cellNumber = ((parseInt($(this).text().split(",").join(""))/totalNumber2)*100).toFixed(2) ;
  }
  else
  {
  	cellNumber = 0;
  }

    //Create new tds for each percentage     
    $('<td></td>')
    .text( cellNumber + '%' ).appendTo('#percentage');

});
			
//Append last td for the new row
$('<td></td>')
   .text('-').appendTo('#percentage');  
@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Roboto');

*{
  font-family: 'Roboto', sans-serif;
  text-transform:capitalize;
  overflow:hidden;
  margin: 0 auto;
  text-align:left;
}

table {
	color:#666;
	font-size:12px;
	background:#e13195;
	border:#ccc 1px solid;
	-moz-border-radius:3px;
	-webkit-border-radius:3px;
	border-radius:3px;
  border-collapse: collapse;
  width: 100%;
}

table td {
	padding:10px;
	border-top: 1px solid #ffffff;
	border-bottom:1px solid #e0e0e0;
	border-left: 1px solid #e0e0e0;
	background: #fafafa;
	background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
	background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
  width: 6.9in;
}

table tbody tr:first-child td
{
	background: #e13195!important;
  color:#fff;
}

table tbody tr th
{
  padding:10px;
  border-left: 1px solid #e0e0e0;
	background: #e13195!important;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<table><tbody><tr><td>Ddddddddd</td><td>Ccccccccc</td><td>Bbbbbbbbb</td><td>Total</td></tr><tr><td>Aaaaaaaaa</td><td>7262</td><td>2723</td><td>9985</td></tr><tr><td>Rate</td><td>56</td><td>55</td><td>56</td></tr></tbody></table>
...