使用带有数据元素的Javascript附加到HTML表

时间:2017-08-01 13:53:22

标签: javascript jquery html

我有四个数组

if (property == value)
    return;

我正在用html制作一个表

arrayOne['orange','blue','green','red','yellow','purple','gray','tan','pink','violet']
arrayTwo['1001','1003','3453','78934','2389','3','8934']
arrayThree['TV','phone','laptop']
arrayFour['1','2','3','4','5','6','7','8','9','10']

我有一个脚本打开一个模态并附加到表我试图让它为两列工作但它只用ArrayOne内容填充第一列

<table class="table table-striped">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
   </tr>
</thead>

使用上面的代码,它只打印出

for (row = 0; row <$(this).data("arrayOne").length; row++ ){
  $("#myModal").find(".table").append("<tr>
  <td>"+$(this).data("arrayOne")[row]+"</td>"); 

  for (j = 0; j <$(this).data("arrayTwo").length; j++ ){
    $("#myModal").find(".table").append("<tr>
    <td>"+$(this).data("arrayTwo")[j]+"</td></tr></tbody></table>");
  } 
} 

最终结果看起来应该是这样的

column1    column2    column 3    column 4
orange
blue
green
red
....
violet

Etc,Etc

7 个答案:

答案 0 :(得分:1)

假设arrayOne包含所有必需的行,而在其他数组上行可能为空,您可以执行类似的操作,

 arrayOne.forEach(function(value, key){
     let firstColumn = arrayOne[key],
         secondColumn = arrayTwo[key]?arrayTwo[key]:"",
         thirdColumn = arrayThree[key]?arrayThree[key]:"",
         fourthColumn = arrayFour[key]?arrayFour[key]:"";

     $("#myModal").find(".table").append('<tr><td>'+firstColumn+'</td><td>'+secondColumn+'</td><td>'+thirdColumn+'</td><td>'+fourthColumn+'</td></tr>');
 });

答案 1 :(得分:1)

你可以试试这个

for (row = 0; row <$(this).data("arrayOne").length; row++ )
{
    var valOne = ($(this).data("arrayOne")[row]!=null)?$(this).data("arrayOne")[row]:"";
    var valTwo = ($(this).data("arrayTwo")[row]!=null)?$(this).data("arrayTwo")[row]:"";
    var valThree = ($(this).data("arrayThree")[row]!=null)?$(this).data("arrayThree")[row]:"";
    var valFour = ($(this).data("arrayFour")[row]!=null)?$(this).data("arrayFour")[row]:"";

    $("#myModal").find(".table").append("<tr><td>"+valOne+"</td><td>"+valTwo+"</td><td>"+valThree+"</td><td>"+valFour+"</td></tr>");
} 

答案 2 :(得分:1)

用于填充表体的jQuery解决方案可以是:

&#13;
&#13;
var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];
for (var i = 0; i <arrayOne.length; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="table table-striped">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您可以使用解决方案https://jsfiddle.net/phru3m7s/1/

&#13;
&#13;
grid.on('beforeedit', function(editor, e) {
  if (e.colIdx === 1 && e.rowIdx === 1)
  {
      return true;
  }
  else 
  {
      return false;
  }
});
&#13;
var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];


for(var i=0; i< arrayOne.length; i++){
	var tableString = "<tr>";
  	tableString += "<td>" + arrayOne[i] + "</td>";
    tableString += "<td>" + ((typeof arrayTwo[i] === 'undefined') ? '' : arrayTwo[i]) + "</td>";
    tableString += "<td>" + ((typeof arrayThree[i] === 'undefined') ? '' : arrayThree[i])  + "</td>";
    tableString += "<td>" + ((typeof arrayFour[i] === 'undefined') ? '' : arrayFour[i]) + "</td>";
  tableString += "<tr>";
  
  $('table tbody').append(tableString);
}
&#13;
&#13;
&#13;

答案 4 :(得分:1)

&#13;
&#13;
function expandTable() {
    var oTable = $('#tblCategories').DataTable();
    oTable.page.len(250).draw();
};
&#13;
var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];

//To test the longest array
var length_array = [];
length_array.push( arrayOne.length); 
length_array.push( arrayTwo.length); 
length_array.push( arrayThree.length); 
length_array.push( arrayFour.length); 

var maxLength = Math.max.apply( null, length_array );

for (var i = 0; i <maxLength; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
&#13;
&#13;
&#13;

答案 5 :(得分:1)

将各个数组合并为一个数组的方法,并确定哪个数组最长然后循环以生成行

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'],
  arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'],
  arrayThree = ['TV', 'phone', 'laptop'],
  arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

var columns = [arrayOne, arrayTwo, arrayThree, arrayFour];
// start from longest column array
var rows = columns.reduce((a, c) => {
    return c.length > a.length ? c : a;
  }, [])
  // map the longest to create all the rows
  .map((_, rowIdx) => {
    // map the cells for each row
    var cells = columns.map(colArr => $('<td>',{text: colArr[rowIdx] || '' }));
    // return new row and cells
    return $('<tr>').append(cells);    
  });
 
// append all the rows     
$('#myModal tbody').append(rows);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
  <table>
     <thead>
        <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
       </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

答案 6 :(得分:1)

使用Array.prototype.reduce()有一种现代且相当优雅的方式,您可以在下面的示例中看到:

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'];
var arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'];
var arrayThree = ['TV', 'phone', 'laptop'];
var arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var sumArray = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
var mergedArrays = [arrayOne, arrayTwo, arrayThree, arrayFour].reduce(function(sum, value, index) {
  for (var key in sum) {
    sum[key][index] = value[key];
  }
  return sum;
}, sumArray);

console.log(mergedArrays);

var htmlToRender = '<table class="table table-striped"><thead><tr><th>Column 1</th><th>Column 2</th><th>Column 3</th><th>Column 4</th></tr></thead><tbody>';

for (var key in mergedArrays) {
  htmlToRender += '<tr><td>' + mergedArrays[key][0] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][1] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][2] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][3] + '</td></tr>';
}

htmlToRender += '</tbody></table>';
$("#myModal").append(htmlToRender);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
</div>

解释

您实际上创建了一个空的对象数组,然后将现有数组的值累加为具有4个值的对象。完成所有操作后,您可以迭代对象数组,并在表中为数组中的每个对象写一个新行。

对于更复杂的情况,可以轻松扩展和调整代码。此外,sumArray的长度可以根据您的需要进行调整和调整。

另外,正如本回答中的评论所指出的,附加结束标记是一种非常糟糕的做法,因此上面的代码使用了更好的代码,渲染整个表而不仅仅是其内容和结束标记。