动态表,在单元格中插入项目,对应于thead排序 [英] Dynamic table, insert items in cells, sorted corresponding to thead

查看:109
本文介绍了动态表,在单元格中插入项目,对应于thead排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,内容是动态的,甚至thead内容也是动态的.

I have a Table, content is dynamic, so is even the thead content.

我有一个对象的列表/数组,称为Ingredients [].

I have a list/array of objects called ingredients[].

项目/对象具有称为类别的属性.

Items/objects have property called category.

我喜欢将此对象数组插入具有与thead列值相对应的属性类别的表中.像这样:

I like to insert this array of objects into the table with the property categories corresponding to the thead columns value. Something like this:

她是我的 演示

Her is my DEMO

我想循环播放广告,看看有什么值(A,B,C,D).然后循环对象数组并将其categ属性与th值匹配,然后将每个对象插入相应的列.

I want to loop thead to see what th value is there (A,B,C,D). Then loop array of objects and match their categ property with th values, then insert each to corresponding column.

许多小时后,许多尝试和爆炸性的动作,我仍然无法完成.请帮忙.

After many hours, many attemps and exploding head, I still can't manage to accomplish this. Please help.

    var categ;
    var name;
    var th;
    var tr=$('<tr>');
    for ( var i in ingredients) {
        tr.appendTo($('#tblGrid'));
        for ( var j in thead) {
            $('<td colspan="2" data-id="" data-catg="'+ingredients[i].categ+'">'+ingredients[i].name+'<span  class="pull-right">kr. '+ingredients[i].price+'</span></td>').appendTo(tr);
                th = thead[j];
                categ= ingredients[i].categ;
                name= ingredients[i].name;                  
                    if (categ==th) {
                        //I am lost 
                    }
            }
        }
});

推荐答案

jQuery是实现此目的的最佳方法,因为它的psuedo选择器可在所有浏览器中使用,并让您真正确定DOM元素,尤其是在处理表时具有动态的行和列.第一个任务是建立一个对所有TD都补偿过度的表(我们可以在所有排序之后删除空行).您创建一系列配料的方法很好,但是我们需要一种在需要的地方传递符合HTML要求的所有属性的方法,以便我们可以安全地进行迭代.

jQuery was the best method to achieve this because its psuedo selectors work across all browsers, and let you really pin-point your DOM elements, especially when dealing with tables that have dynamic rows and columns. The first task was to build up a table overcompensated for all of the TDs (where we can remove empty rows after all the sorting). Your approach at creating an array of ingredients was fine, but we needed a way to pass in all attributes where needed that was HTML compliant so we could safely iterate.

工作演示

var ingredients = [];

function addIngredToList(id, name, price, categ) {
  var item = [];
  item.push(id);
  item.push(name);
  item.push(price);
  item.push(categ);
  ingredients.push(item);
}

然后,既然我们将所有TD信息存储在可以迭代的数组中,那么我们就可以动态构建TD.我们会在新行中创建表格后立即将它们放入表格中(在必要的地方创建空白TD,以保持表格顺序井然有序).

Then we dynamically build up the TDs now that we have all the information for them in an array that we can iterate over. We put them into the table as soon as it is created in a new row (creating blank TDs where necessary to keep the table flow in order).

for (i = 0, z = ingredients.length; i < z; i++) {
  var emptyRow = "<tr class='emptyRow'></tr>";
  $('table#tblGrid').append(emptyRow);
  emptyRowSelector = $('tr.emptyRow');
  for (c = 0, b = ingredients[i].length; c < b; c++) {
    var columnID = " " + $('table#tblGrid').find('th').eq(c).text().toLowerCase().toString();
    var emptyTD = "<td colspan='2' class='emptyTD" + columnID + "'></td>";
    emptyRowSelector.eq(i).append(emptyTD);
  }
}

//Create a TD  with ingredient array attributes.
var $rowScanner = $('table#tblGrid').find('tr').not($('tr:eq(0)'));
var $headerScanner = $('table#tblGrid').find('tr:eq(0) th');

for (g = 0, e = $rowScanner.length; g < e; g++) {
  var idCol = ingredients[g][0];
  var nameCol = ingredients[g][1];
  var priceCol = ingredients[g][2];
  var categCol = ingredients[g][3];

  var tdCell = "<td colspan='2' data-id='" + idCol + "' data-catg='" + categCol + "' class='" + categCol.toLowerCase().toString() + "'>" + nameCol + "<span class='pull-right'>kr." + priceCol + "</span></td>";
  var classChecker = "td." + ingredients[g][3].toString() + "";
  $rowScanner.eq(g).find(classChecker).replaceWith(tdCell).addClass("targetFound");
}

$headerScanner.each(function(i, v) {
  var assignClass = $(this).text();
  $(this).addClass(assignClass).attr("colspan", "2");
});

最后,借助于 Jean-Claude ,我能够创建一个临时表,其中包含所有TD及其属性,并将它们按升序排序回到主表网格中.然后,在完成所有过程之后,我创建了一个间隔,该间隔扫描页面中的空表行,并将其删除.

Lastly, with the help of Jean-Claude, I was able to create a temporary table that held all the TDs with their attributes and sort them back into the master table grid in ascending order. Then, after all processes were done, I created an interval that scanned the page for empty table rows, and remove them.

此代码在设置时就考虑到了自动化,因此它非常通用,其中唯一需要根据情况进行调整的项是表单元格的变量和属性.

This code was setup with automation in mind, so it is pretty versatile, where the only items that need to be tweaked on a case by case basis are the variables and attributes for the table cells.

var ingredients = [];

function addIngredToList(id, name, price, categ) {
  var item = [];
  item.push(id);
  item.push(name);
  item.push(price);
  item.push(categ);
  ingredients.push(item);
}

addIngredToList(1, "Ooo", 8, "a");
addIngredToList(7, "Pppp", 10, "b");
addIngredToList(12, "Kkkk", 6, "c");
addIngredToList(2, "Ffff", 8, "a");
addIngredToList(4, "Ssss", 10, "b");
addIngredToList(15, "Vvvv", 6, "c");
addIngredToList(5, "Iiii", 10, "b");
addIngredToList(21, "Llll", 6, "c");
addIngredToList(22, "Mmmm", 9, "a");
addIngredToList(7, "Bbbb", 12, "b");
addIngredToList(8, "Eeee", 8, "b");
addIngredToList(9, "Gggg", 6, "c");
addIngredToList(10, "Cccc", 6, "c");
addIngredToList(11, "Aaaa", 6, "c");
addIngredToList(6, "Nnnn", 10, "b");
addIngredToList(3, "Zzzz", 8, "a");
addIngredToList(13, "Mmmm", 6, "c");
addIngredToList(14, "Rrrr", 6, "c");
addIngredToList(17, "Hhhh", 5, "d");
addIngredToList(18, "Uuuu", 5, "d");
addIngredToList(19, "Qqqq", 5, "d");
addIngredToList(20, "Xxxx", 5, "d");

//Create Rows Empty Rows and TDs with appropiate classes in each column
for (i = 0, z = ingredients.length; i < z; i++) {
  var emptyRow = "<tr class='emptyRow'></tr>";
  $('table#tblGrid').append(emptyRow);
  emptyRowSelector = $('tr.emptyRow');
  for (c = 0, b = ingredients[i].length; c < b; c++) {
    var columnID = " " + $('table#tblGrid').find('th').eq(c).text().toLowerCase().toString();
    var emptyTD = "<td colspan='2' class='emptyTD" + columnID + "'></td>";
    emptyRowSelector.eq(i).append(emptyTD);
  }
}

//Create a TD  with ingredient array attributes.
var $rowScanner = $('table#tblGrid').find('tr').not($('tr:eq(0)'));
var $headerScanner = $('table#tblGrid').find('tr:eq(0) th');

for (g = 0, e = $rowScanner.length; g < e; g++) {
  var idCol = ingredients[g][0];
  var nameCol = ingredients[g][1];
  var priceCol = ingredients[g][2];
  var categCol = ingredients[g][3];

  var tdCell = "<td colspan='2' data-id='" + idCol + "' data-catg='" + categCol + "' class='" + categCol.toLowerCase().toString() + "'>" + nameCol + "<span class='pull-right'>kr." + priceCol + "</span></td>";
  var classChecker = "td." + ingredients[g][3].toString() + "";
  $rowScanner.eq(g).find(classChecker).replaceWith(tdCell).addClass("targetFound");
}

$headerScanner.each(function(i, v) {
  var assignClass = $(this).text();
  $(this).addClass(assignClass).attr("colspan", "2");
});

//Create a temporary table to hold and sort cells.
$("<table style='display:none;' class='temp'><tr><td class='placeHolder'>Place Holder</td></tr></table>").prependTo($('body'));

$rowScanner.find('td').not('td:empty').each(function() {
  var $cloneIt = $(this).clone();
  $cloneIt.appendTo($('table.temp tr'));
  var whitelist = ["class", "colspan"];
  var attributes = this.attributes;
  var i = attributes.length;
  while (i--) {
    var attr = attributes[i];
    if ($.inArray(attr.name, whitelist) == -1)
      this.removeAttributeNode(attr);
  }
  $(this).html("");
});

$('td.placeHolder').remove();
$('#tblGrid').find('td').removeClass("emptyTD");

//This section was solved by Jean-Claude of StackOverflow
//Sort TDs back into correct columns from the temporary table
//https://stackoverflow.com/questions/37120353/transpose-array-of-tds-into-columns-jquery/37121225#37121225
$(function() {
  var $tempScanner = $('table.temp tr td');
  var tempArry = [];

  $tempScanner.each(function(i, el) {
    var d = {};
    d.text = $(el).text();
    d.html = $(el).html();
    d.class = $(el).attr('class');
    tempArry.push(d);
  });

  function compareObj(o1, o2) {
    return o1.text > o2.text;
  }

  tempArry = tempArry.sort(compareObj);
  console.log(tempArry);

  for (var i = 0; i < tempArry.length; i++) {
    var tdClass = tempArry[i].class;
    $('#tblGrid td.' + tdClass + ':empty:first').html(tempArry[i].html).addClass('sorted');
  }
});

//Remove Empty Rows
var removeEmpty = setInterval(function() {
  var emptyTD = $('td.sorted');
  if (emptyTD.length > 0) {
    $rowScanner.each(function() {
      if ($(this).find(emptyTD).length > 0) {

      } else {
        $(this).remove();
        $('table.temp').remove();
      }
    });
    console.log(emptyTD.length);
    clearInterval(removeEmpty);
  } else {
    var doNothing = "";
  }
}, 50);

td,
th {
  border: 1px solid #111;
  padding: 6px;
}
th {
  font-weight: 700;
}
span.pull-right {
  float: right;
  text-align: right;
}
.a,
.A {
  background-color: #ACE;
}
.b,
.B {
  background-color: #FAF;
}
.c,
.C {
  background-color: #BAB;
}
.d,
.D {
  background-color: #ECA;
}
.targetFound {
  border: solid 2px red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="tblGrid">
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
    <th>D</th>
  </tr>
</table>

这篇关于动态表,在单元格中插入项目,对应于thead排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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