如何根据数组中的数据动态创建表

时间:2017-07-22 20:21:27

标签: javascript html

var arr=["1","2","-3","4","-5","-6","7"]  //  data changes as well arr[] size ;

在这里,情节是,我在表格中动态制作。表格取决于arr[]

1)创建一行<tr> <td></td></tr>,,其中<td> </td>的数量取决于arr[];的长度

2)提供style="background-color" to <td>;

3)对于负数,<td>将创建index of that negative number

例如:这里negative number indexes are 3,5,6.  因此,对于否定numbers in arr[],请在<td>的下一行创建<tr><td></td></tr><td> 3,5,6 position background-color.   在此-3,-5,-6 arr[] <td>创建first row <tr> background-color,但不提供//length of arr = 7; <tr> <td style="background:#ccc">1</td> <td style="background:#ccc">2</td> <td style="background:#ccc"></td> <td style="background:#ccc">4</td> <td></td> <td></td> <td style="background:#ccc">7</td> </tr> <tr> <td></td> <td></td> <td style="background:#ccc">-3</td> <td></td> <td style="background:#ccc">-5</td> <td style="background:#ccc">-6</td> <td></td> </tr> The above scenario will change according to data. Please help ;

4)如果arr []中没有负数,则不要创建第二行;

这里,arr []数据正在变化,因此表格应该是动态的。

对于上述情况,只有少数代码只能理解

ko.bindingHandlers.Loading = {
init: function (element) {
    $(element).append("<div id='loading_wrap' class='loader' style='height:100%; width:100%;text-align:center; margin-top: 20%'><img src='./resources/ajax-loader.gif'><br>Loading, please wait.</div>")
},
update: function (element, valueAccessor) {
    var isLoading = ko.utils.unwrapObservable(valueAccessor());
    var $element = $(element);
    var $children = $element.children(':not(.loader)');
    var $loader = $(element).find('.loader');

    if (isLoading) {
        $children.hide();
        $loader.show();
    } else {
        $children.show();
        $loader.hide();

    }
}

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var arr = ["1","2","-3","4","-5","-6","7"];

var table = document.createElement("table"),          // create the table element
    tbody = document.createElement("tbody");          // create the table body element
    
table.appendChild(tbody);                             // add the table body to table

// ### POSITIVE ROW ######################

var tr = document.createElement("tr");                // create the table row element
arr.forEach(function(e) {                             // for each element e in arr
  var td = document.createElement("td");              // create a table cell element
  if(e >= 0) {                                        // if e is positive
    td.textContent = e;                               // then change the text content of this cell to e
    td.style.background = "#ccc";                     // and change the background as well
  }
  tr.appendChild(td);                                 // add the cell to the row (if the number is negative the cell will be empty and without background)
});
tbody.appendChild(tr);                                // add the row to table


//### NEGATIVE ROW ######################

tr = document.createElement("tr");                    // same but for negative numbers ...
arr.forEach(function(e) {
  var td = document.createElement("td");
  if(e < 0) {
    td.textContent = e;
    td.style.background = "#ccc";
  }
  tr.appendChild(td);
});
tbody.appendChild(tr);

document.body.appendChild(table);
&#13;
&#13;
&#13;

您可以将函数中的一些代码分组并重复使用它:

&#13;
&#13;
// elt is shortcut for document.createElement
function elt(tag) {
  return document.createElement(tag);
}

// take an array and a condition function conditionFN and return a row of all the element that passed the condition function with a background of #ccc
function makeRow(arr, conditionFN) {
  var tr = elt("tr");
  arr.forEach(function(e) {
    var td = elt("td");
    if (conditionFN(e)) {
      td.textContent = e;
      td.style.background = "#ccc";
    }
    tr.appendChild(td);
  });
  
  return tr;
}

// take an array and return the equivalent table element
function makeTable(arr) {
  var table = elt("table"),
      tbody = elt("tbody");

  table.appendChild(tbody);
  
  tbody.appendChild(makeRow(arr, function(e) { return e >= 0; })); // the condition function only allows positive numbers => positive row
  tbody.appendChild(makeRow(arr, function(e) { return e < 0; }));  // the condition function only allows negative numbers => negative row
  
  return table;
}



document.body.appendChild(makeTable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试用此代码:

&#13;
&#13;
var array=["1","2","-3","4","-5","-6","7"];

//creating table element---------
var table = document.createElement("table"),
tbody = document.createElement("tbody");

//append to table---------
table.appendChild(tbody);      
tbody.innerHTML=getTr(array);

//append to document---------
document.body.appendChild(table);


//console.log(getTr(arr));

//getting all tr---------
function getTr(arr,color='#ccc'){
  var ptd='',ntd ='';
  for(i=0;i<arr.length;i++){
     var std='<td style="background-color:'+color+';">';
     ptd += (arr[i]>=0)? std + arr[i]+'</td>':'<td></td>';
     ntd += (arr[i]<0)? std + arr[i]+'</td>':'<td></td>';
  }
  return '<tr>'+ptd+'</tr>'+'<tr>'+ntd+'</tr>';
}
&#13;
&#13;
&#13;

您可以使用函数

查看简化代码结果

&#13;
&#13;
//appending table to document------
document.body.appendChild(mktable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));


//creating table element---------
function mktable(array){
    var table = document.createElement("table"),
    tbody = document.createElement("tbody");  
    tbody.innerHTML=getTr(array);
    table.appendChild(tbody);
    return table;
}


//getting all tr---------
function getTr(arr,color='#ccc'){
  var ptd='',ntd ='';
  for(i=0;i<arr.length;i++){
     var std='<td style="background-color:'+color+';">';
     ptd += (arr[i]>=0)? std + arr[i]+'</td>':'<td></td>';
     ntd += (arr[i]<0)? std + arr[i]+'</td>':'<td></td>';
  }
  return '<tr>'+ptd+'</tr>'+'<tr>'+ntd+'</tr>';
}
&#13;
&#13;
&#13;

  

注意:这很简单,重量轻

答案 2 :(得分:0)

使用递归函数和table.inertRow()以及row.insertCell()

&#13;
&#13;
var data = ["1", "2", "-3", "4", "-5", "-6", "7"];
var table = document.getElementById('myTable')

function plusMinusRows(arr, rowNum) {      
  var row = table.insertRow();
  arr.map(Number).forEach(function(num) {
    var value = !rowNum  ? (num >= 0 ? num : '') : (num < 0 ? num : '');
    var cell = row.insertCell();
    cell.textContent = value;
    cell.style.background = value !== '' ? '#cccccc' : '';
  });
  // call function again when rowNum  not defined
  !rowNum && plusMinusRows(arr, 2);
}
// initialize 2 rows
plusMinusRows(data);
&#13;
<table id="myTable"></table>
&#13;
&#13;
&#13;