繁体   English   中英

初始Handlebars.js无功能

[英]Initial Handlebars.js None Functionality

我正在尝试学习Handlebars.js(第一个小时),而且似乎遇到了一个最初的问题(它不起作用)。

这是我的html:

<!doctype html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
    <script src="js/handlebars-v4.0.5.js"></script>
    <script src="js/main.js"></script>
</head>

<body>
    <p>Hi!</p>
    <script id="some-template" type="text/x-handlebars-template">
        <table>
            <thead>
                <th>Username</th>
                <th>Real Name</th>
                <th>Email</th>
            </thead>
            <tbody>
                {{#users}}
                <tr>
                    <td>{{username}}</td>
                    <td>{{firstName}} {{lastName}}</td>
                    <td>{{email}}</td>
                </tr>
                {{/users}}
            </tbody>
        </table>
    </script>
</body>

</html>

这是我的main.js:

$(document).ready(function() {
    console.log("I'm Here!");
    var source = $("#some-template").html();
    var template = Handlebars.compile(source);
    var data = {
        users: [{
            username: "alan",
            firstName: "Alan",
            lastName: "Johnson",
            email: "alan@test.com"
        }, {
            username: "allison",
            firstName: "Allison",
            lastName: "House",
            email: "allison@test.com"
        }, {
            username: "ryan",
            firstName: "Ryan",
            lastName: "Carson",
            email: "ryan@test.com"
        }]
    };
    $("#content-placeholder").html(template(data));
});

我看到控制台日志,但是表根本没有写。 没有控制台错误消息,而且我对卡在哪里有些困惑。

希望这不是造成打字错误等明显疲劳的原因。

为了使代码按原样工作,您需要在文档中定义一个与#content-placeholder匹配的HTML元素,以便$("#content-placeholder").html(template(data)); 有一个放置渲染模板的地方。

您可以通过将其添加到HTML中来解决此问题,如下所示:

<!doctype html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
    <script src="js/handlebars-v4.0.5.js"></script>
    <script src="js/main.js"></script>
</head>

<body>
    <p>Hi!</p>
    <script id="some-template" type="text/x-handlebars-template">
        <table>
            <thead>
                <th>Username</th>
                <th>Real Name</th>
                <th>Email</th>
            </thead>
            <tbody>
                {{#users}}
                <tr>
                    <td>{{username}}</td>
                    <td>{{firstName}} {{lastName}}</td>
                    <td>{{email}}</td>
                </tr>
                {{/users}}
            </tbody>
        </table>
    </script>

    <!-- Add this line -->
    <div id="content-placeholder"></div>
</body>

</html>

我变了

$("#content-placeholder").html(template(data));

$('body').append(template(data));

我得到了期望的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM