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

标签 javascript jquery 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']

我正在用html制作一个表格

<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>

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

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

最终结果应该是这样的

column1    column2    column 3    column 4
orange     1001       TV          1
blue       1003       phone       2
green      3453       laptop      3
red        78934                  4
yellow     2389                   5

等等

最佳答案

假设 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>');
 });

关于javascript - 使用带有数据元素的 Javascript 附加到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439840/

相关文章:

javascript - Display CSS 属性设置为 none 后视频自动播放

javascript - 设置 Canvas 背景颜色

c# - 无法从代码隐藏中调用 JS 函数

javascript - 由于显示 :flex;,SmartMenus 在 Chrome 上无法正常工作

javascript - 尝试使用 Google API Node.js 客户端时出现 "Module not found"错误

java - 在 javascript 调用函数中,同时必须调用 java 函数

javascript - append 具有从 PHP 返回的特定 ID 的按钮不起作用

Javascript 数组不会更新

javascript - 我们如何将数据发送到 Node js中与数据库调用异步的局部变量

jQuery 函数替换臃肿的代码