从外部文件加载 bootstrap table

Load bootstrap table from external file

我想在索引页上加载 table.html 文件,其中包含 table 和 bootstrap 类。问题是它在加载 table 后没有获得样式。是什么原因? 如果我在 table.html 文件中导入 bootstrap 库,我的问题将得到解决,但这个解决方案不是 suitable 因为对于每个 bootstrap 库调用被加载,我想要在索引页面中只导入一次所需的库,每次我的 table 加载它。

这是我的代码:(你也可以看到https://github.com/yarandish/Challanges

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
        var cache = null;
    </script>

    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.rtl.min.css">
    <link rel="stylesheet" href="lib/table/bootstrapTable/css/bootstrap-table.min.css">

    <script src="lib/jquery/jquery-3.6.0.min.js"></script>
    <script src="lib/bootstrap/js/bootstrap.min.js"></script>
    <script src="lib/table/bootstrapTable/js/bootstrap-table.min.js"></script>

</head>
<body>
    <input type="text" id="name">
    <input type="text" id="price">
    <input type="text" id="age">
    <button onclick="cache = $('body'); $('body').load('table.html');">load table</button>
</body>
</html>

table.html :

<table 
    id="table"
    data-toggle="table"
    data-url="data.json"
    data-buttons-class="outline-secondary"
    data-classes="table table-striped table-hover table-bordered"
    data-toolbar=".toolbar" data-maintain-meta-data="true" tabindex="-1"
    data-click-to-select="true"
    data-multiple-select-row="true"
    >
    <thead>
        <tr>
            <th data-checkbox="true"></th>
            <th data-field="name">name</th>
            <th data-field="price">price</th>
            <th data-field="day">day</th>
        </tr>
    </thead>
</table>

Due to the widespread use of tables across third-party widgets like calendars and date pickers, we’ve designed our tables to be opt-in. Just add the base class .table to any , then extend with custom styles or our various included modifier classes. ref

因此您需要手动将这些 classes 添加到 HTML 标记:

  • table class 到 table 元素
  • col class 每个 td/th 元素
  • row class 到每个 tr 元素。

replit

上的工作演示

添加新内容时需要重新运行脚本。只需在 table.html 末尾添加以下代码:

<script>
  $('[data-toggle="table"]').bootstrapTable();
</script>

这是 codepen 上的工作 demo

如果您不想定位所有表,那么您还可以使用:

$('#table').bootstrapTable();