jquery 数据表计算所有不同的品种

flseospp  于 2023-03-07  发布在  jQuery
关注(0)|答案(1)|浏览(128)

在我的datatable中,我尝试计算一列的所有不同类型。在下面的示例中,我希望输出计算yes、no,然后将所有yes、no加在一起。我尝试了fnFooterCallback,但没有得到值。

Output 
Yes 1
No  2
Total Votes (Y+N)   3

x一个一个一个一个x一个一个二个x

lb3vh1jj

lb3vh1jj1#

使用下面的vanilla JS看起来能满足你的需求。如果你能控制的话,使用不同的html结构会简单得多。但是这会给你一个原型来工作和重构以满足你的需求。

const 
  //get the answers as an array
  answers = Array.prototype.slice.call(document.querySelectorAll('.answers td')).map(function (a) {   return a.innerText; }),
  //get the questions as an array
  questions = Array.prototype.slice.call(document.querySelectorAll('.questions th')),
  //get the length of the questions
  qLen = questions.length,
  //create a dictionary object
  dict = {};
let arr;
//loop the questions array
questions.forEach(function (q, i) {
  //set the var arr to an array of answers matching the column of the question
  arr = answers.filter(function (a, ai) { return (ai - i) % qLen == 0; });
  //set the dictionary line to an empty object
  dict[q.innerText] = {};
  arr
    //uniquify the answers
    .filter(function (x, i) { return arr.indexOf(x) === i; })
    //loop the uniquified answers to set the dictionary.question = the answer
    //then set the dictionary.question.answer = count
    .forEach(function (x) { dict[q.innerText][x] = arr.filter(function(a) { return a == x; }).length; });
});
//result is a dictionary that can be drilled down into a count via dict.question.answer
console.log(dict);
<table id="question">
  <tr class="questions">
    <th>Question 1</th>
    <th>Question 2</th>
    <th>Question 3</th>https://stackoverflow.com/questions/75522879/datatable-count-all-the-different-varieties#
  </tr>
  <tr class="answers">
    <td>Yes</td>
    <td>Hot</td>
    <td>Yes</td>
  </tr>
  <tr class="answers">
    <td>No</td>
    <td>Cold</td>
    <td>Yes</td>
  </tr>
  <tr class="answers">
    <td>No</td>
    <td>Hot</td>
    <td>Yes</td>
  </tr>
</table>

相关问题