您如何为html表建立行排序(水平排序)? [英] How do you build a row sorting (Horizontal sort) for html table?

查看:69
本文介绍了您如何为html表建立行排序(水平排序)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在jquery中实现一个功能,在该功能中,用户单击第一行,并对单击的行中的其余项进行排序. 我在这里准备了一个Codepen https://codepen.io/shaikh709/pen/orNLaY ?editors = 0010

I need to implement a functionality in jquery where a user clicks on very first row and sort remaining items in clicked row. I've prepared a codepen here https://codepen.io/shaikh709/pen/orNLaY?editors=0010

这是我要对表格进行排序的js

Here is the js I've for sorting table

function sortRow(rowIndex) {

    let table               = $('.report')
    let tr                  = table.find('tr');
    let selectedRow         = $(tr[rowIndex]);
    let selectedRowTd       = selectedRow.find('td');
    let selectedRowSorting  = [];

    // find and get clicked tr and it formats it in index and value of the cells
    selectedRowTd.each(function(tdIndex){
        let td = $(selectedRowTd[tdIndex]);
        selectedRowSorting.push({
            tdIndex: tdIndex,
            value: parseInt(Math.ceil(td.text().trim()))
        })
    })


    // it will compare values and sort
    selectedRowSorting = selectedRowSorting.sort(function(a, b){

        if (a.value == 0) {
            return -1;
        }

        if (b.value == 0) {
            return -1;
        }

        return b.value - a.value
    });

    console.log(selectedRowSorting)

    // it will only return indexs of sorted list of cells
    var sortedIndexs = selectedRowSorting.map(function(rowSorting){
        return rowSorting.tdIndex
    })

    console.log(sortedIndexs)

    table.find('tr').each(function(){
        let tr = $(this);
        let modifiedTr = [];

        tr.children().each(function(tdIndex, td){

          if (tdIndex == 0) {
            console.log(td)           
            modifiedTr[0] = td;

          } else {
            for (let i =0; i < sortedIndexs.length;i++) {
              console.log(sortedIndexs[i])
              // it gives me index of sorted column.
              if (tdIndex == i) {
                let sortedIndex = sortedIndexs[i];

                if ( sortedIndex == undefined) {
                  console.log('i', i, sortedIndex)
                  sortedIndex = sortedIndexs.length+1
                }

                modifiedTr[sortedIndex] = td;
              }
            }
          }

        })

        tr.append(modifiedTr)
    })
}

我已经在此处创建了一个演示 https://codepen.io/shaikh709/pen/orNLaY?editors = 0010

I've created a demo here https://codepen.io/shaikh709/pen/orNLaY?editors=0010

当用户单击连续的第一个(非常左侧)单元格时.我希望该行的其余部分切换为最大值到最小值.

When user click on first (very left) cell in a row. I want rest of the row to switch to largest to smallest value.

被困在这里约两天.任何帮助表示赞赏.谢谢. :)

Been stuck here for about couple of days. Any help is appreciated. Thanks. :)

推荐答案

我会保持简单,只构建一个小的值数组,然后在该数组上使用.sort().

I would keep it simple and just build a small Array of the values, and then use .sort() upon the Array.

工作示例: https://jsfiddle.net/Twisty/ondf3ram/

JavaScript

$(function() {
  function sortDesc(a, b) {
    return a - b;
  }

  function sortAsc(a, b) {
    return b - a;
  }

  function sortRow(rObj, desc) {
    var curArr = [];
    $("td", rObj).each(function(i, el) {
      curArr.push(parseInt($(el).text().trim()));
    });
    if (desc == undefined || desc == true) {
      curArr.sort(sortDesc);
    } else {
      curArr.sort(sortAsc);
    }
    $("td", rObj).each(function(i, el) {
      $(el).html(curArr[i]);
    });
  }

  $(".sortable tbody th").on("click", function(e) {
    var r = $(this).parent();
    if ($(this).data("sort") == undefined) {
      $(this).data("sort", true);
    }
    sortRow(r, $(this).data("sort"));
    $(this).data("sort", $(this).data("sort") ? false : true);
  });
});

使用适当的选择器会对您有很大帮助!我不确定您是否要将降序转换为升序.所以这是我追求的目标:

Making use of the proper Selectors will help you a lot! I wasn't sure if you wanted to reverse the sort Descending to Ascending. So here are the goals I went for:

  • 单击<tbody>中的<th>(第一个)单元格,以执行父级<tr>
  • 最初使用降序排序
  • 其他点击将在Desc中切换排序.到Asc.
  • Click on <th> (first) cell in the <tbody> to execute a sort of the parent <tr>
  • Initially sort with Descending Sort
  • Additional clicks will toggle the sort from Desc. to Asc.

为此,我们具有sortRow()函数,该函数需要jQuery <tr> Object . (可选)它可以接受排序方向作为布尔值(默认值:truetrue = Desc./false = Asc).它执行排序,不返回任何内容.

To this effect we have the sortRow() function that expects a jQuery <tr> Object. Optionally it can accept a sort Direction as a Boolean (Default: true, true = Desc. / false = Asc). It performs the sort and does not return anything.

我创建了一个数组,并使用.each()函数填充它,以遍历目标<tr>中的每个<td>.由于获取单元格的.text()或Text节点,因此我使用.trim()删除所有空白,然后使用parseInt()填充整数.

I created an Array and populated it using the .each() function to iterate over each <td> in the <tr> that is targeted. Since I am getting the .text() or Text node of the cell, I use .trim() to drop any white space and then use parseInt() to populate the Array with Integers.

然后我们根据比较函数对数组进行排序:

We then Sort the Array based on compare function:

定义替代排序顺序的函数.该函数应返回一个负值,零值或正值,具体取决于参数.

A function that defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments.

然后,我们再次重复相同的单元格并替换数组中的内容.全部完成!

We then re-iterate the same cells and replace the content from the array. All done!

我通过在每一行上查找.data()添加了切换功能.如果这是第一次点击,将没有数据,因此我们假定为Desc.种类.下次我们单击该行标题时,它将具有一个值并切换到Asc.排序.

I added the toggle feature by looking for .data() on each row. If this is the first click, there will be no data, so we assume a Desc. sort. The next time we click on that row header, it will have a value and toggle to an Asc. sort.

更新

请不要发表您的评论,听起来您想对Martix进行分类.在这里讨论:如何按列值对二维数组进行排序?

Base don your comments, it sounds like you want to sort a Martix. This is discussed here: How to sort 2 dimensional array by column value?

工作示例: https://jsfiddle.net/Twisty/ondf3ram/70/

JavaScript

$(function() {

  var selInd;

  function sortMatrixDesc(a, b) {
    if (a[selInd] === b[selInd]) {
      return 0;
    } else {
      return (a[selInd] < b[selInd]) ? -1 : 1;
    }
  }

  function sortMatrixAsc(a, b) {
    if (a[selInd] === b[selInd]) {
      return 0;
    } else {
      return (a[selInd] > b[selInd]) ? -1 : 1;
    }
  }

  function getTblCont(tb) {
    var cols = [];
    $("tr:first td", tb).each(function(i, el) {
      cols[i] = [];
    });
    for (var c = 0; c < cols.length; c++) {
      $("tr", tb).each(function(i, el) {
        cols[c].push(parseInt($("td", el).eq(c).text().trim()));
      });
    }
    return cols;
  }

  function sortRow(rObj, desc) {
    var tblObj = getTblCont(rObj.parent());
    var rowInd = rObj.index();
    if (desc == undefined || desc == true) {
      tblObj.sort(sortMatrixDesc);
    } else {
      tblObj.sort(sortMatrixAsc);
    }
    rObj.parent().find("tr").each(function(r, tr) {
      $("td", tr).each(function(i, el) {
        $(el).html(tblObj[i][r]);
      });
    });
  }

  $(".sortable tbody th").on("click", function(e) {
    var r = $(this).parent();
    selInd = r.index();
    if ($(this).data("sort") == undefined) {
      $(this).data("sort", true);
    }
    sortRow(r, $(this).data("sort"));
    $(this).data("sort", $(this).data("sort") ? false : true);
  });
});

希望有帮助.

这篇关于您如何为html表建立行排序(水平排序)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆