动态表,在单元格中插入项目,对应于thead排序

时间:2016-05-05 19:40:42

标签: jquery

我有一个表,内容是动态的,所以甚至是thead内容。

我有一个名为ingredients []的对象列表/数组。

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

我喜欢将这个对象数组插入到表中,其属性类别对应于thead列的值。像这样:

enter image description here

她是我的 DEMO

我想循环thead以查看其中的值(A,B,C,D)。然后循环对象数组并将其属性与th值匹配,然后将每个属性插入相应的列。

经过几个小时,许多尝试和爆炸头,我仍然无法实现这一目标。请帮忙。

    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 
                    }
            }
        }
});

1 个答案:

答案 0 :(得分:1)

jQuery是实现这一目标的最佳方法,因为它的psuedo选择器适用于所有浏览器,并且让您真正精确定位DOM元素,尤其是在处理具有动态行和列的表时。第一个任务是为所有TD建立一个过度补偿的表(我们可以在所有排序后删除空行)。你创建一系列成分的方法很好,但是我们需要一种方法来传递所有需要符合HTML的属性,这样我们就可以安全地进行迭代。

Working Demo

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以保持表流顺序)。

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及其属性,并按升序将它们排序回主表格。然后,在完成所有进程后,我创建了一个区间,用于扫描页面中的空表行,并将其删除。

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

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>