【问题标题】:Can we create multiple HTML tables dynamically using for loop in jquery我们可以在jquery中使用for循环动态创建多个HTML表吗
【发布时间】:2017-06-09 06:44:52
【问题描述】:

我想动态创建 html 表,表的数量将取决于我在数组中得到的响应。每 6 个元素后应创建新表,表头将是数组元素本身。 预期输出是-

-------------------------------------
| th1 | th2 | th3 | th4 | th5 | th6 |
-------------------------------------
|     |     |     |     |     |     |
-------------------------------------

生成表格的代码如下,其中控制台打印正常,但元素没有被创建,也没有出现任何错误。

'<div id="findingDiv">';

    for(var i=0;i<tables;i++){
         console.log('i-',i);                               
        '<table class="table table-bordered" style="margin-top: 10px; border:1px solid black; border-collapse : collapse;font-size: 30px;">'+
            '<thead>'+
                '<tr>';

                for(var k=0;k<6;k++){   

                    '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);"> historyTable[k] </th>';
                    console.log('k-',k);
                }

       '</table> \n';                               
    }

有人可以帮帮我吗?

我已经检查了以前没有用的解决方案。 How to clone() a element n times? How to use loop in Jquery to add table multiple times into div Create a table dynamically using for loop in .html()

【问题讨论】:

标签: jquery html bootstrap-4


【解决方案1】:

您可以使用 jQuery .append() 方法在for 循环中动态地将HTML 表添加到您的DIV

Working fiddle

您可以使用以下代码。

在 html 中的 DIV 下方:

<div id="findingDiv">
</div>

jquery 中的代码。我使用 jQuery .ready() 方法在页面加载时创建它:

$(document).ready(function () {
    var tables = ['th1','th2','th3','th4','th5','th6']

    for(var i=0;i<tables.length;i++){
    var content = "<table><thead><tr>";
        for(var k=0;k<6;k++)
        {
            content += '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);">'+tables[k]+' </th>';                    
        }
        content += "</tr></thead></table><br/>";
        $('#findingDiv').append(content);
    }
 });

我刚刚添加了th,您也可以添加tr

【讨论】:

  • 是的 thnx ..但是当 divfindingDiv 在 html 代码中定义时它正在工作。我无法在 html 中创建 div 我需要在点击事件上动态创建它。在这种情况下,这是行不通的。
  • 好吧,在这种情况下,您也可以在 jquery 中创建 DIV。但是您需要在任何元素上使用 .append(content) ,可能是一个主体。因为你不能直接将元素注入 DOM。
猜你喜欢
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
相关资源
最近更新 更多