Bootstraptable 使用js初始化不成功

小白一名,这段代码是从BootStraptable介绍页上直接复制下来的,但是还是无法初始化,Console里没有报错,Network里也没有404错误,请问如何才能使用js初始化表格?不甚感激

<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-table.css">
    <script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-table.js"></script>
<!-- put your locale files after bootstrap-table.js -->
<script src="js/bootstrap-table-zh-CN.js"></script>
<script>
    $('#table').bootstrapTable({
    columns: [{
        field: 'id',
        title: 'Item ID'
    }, {
        field: 'name',
        title: 'Item Name'
    }, {
        field: 'price',
        title: 'Item Price'
    }],
    data: [{
        id: 1,
        name: 'Item 1',
        price: '$1'
    }, {
        id: 2,
        name: 'Item 2',
        price: '$2'
    }]
});
</script>

        <title></title>
    </head>
    <body>
        <table id="table"></table>
    </body>
</html>
阅读 6.2k
1 个回答

你的脚本执行的时候dom还没有加载完,取不到id="table"的jQuery对象。
当前案例中最简单的解决办法是将你的脚本放到body标签的最后面。

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-table.css">
    </head>
    <body>
        <table id="table"></table>
        <script src="js/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/bootstrap-table.js"></script>
        <!-- put your locale files after bootstrap-table.js -->
        <script src="js/bootstrap-table-zh-CN.js"></script>
        <script>
            $('#table').bootstrapTable({
                columns: [{
                    field: 'id',
                    title: 'Item ID'
                },
                {
                    field: 'name',
                    title: 'Item Name'
                },
                {
                    field: 'price',
                    title: 'Item Price'
                }],
                data: [{
                    id: 1,
                    name: 'Item 1',
                    price: '$1'
                },
                {
                    id: 2,
                    name: 'Item 2',
                    price: '$2'
                }]
            });
        </script>
    </body>
</html>

因为默认的js加载和执行是阻塞dom渲染的,因此你应该总是将js的引入和内嵌的js脚本放到body的最后。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题