骨干代码不能渲染简单的View

时间:2014-07-25 14:46:15

标签: javascript backbone.js

简单主干视图不在元素内部渲染,并且没有错误

<html>
    <head>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.9/backbone-min.js"></script>
    </head>

    <body>
        <script type="text/javascript">
            var SearchView = Backbone.View.extend({
                el: '.container',
                initialize: function() {
                    this.render();
                },
                render: function() {
                    $(this.el).html("hello"); //tried both but not working. 
                    this.$el.html("hello"); 
                } 
             }); 
             var search_view = new SearchView();
        </script>
        <div class="container"></div>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

您的问题是因为您没有等待DOM准备好,请尝试移动这样的div(http://jsfiddle.net/icodeforlove/68gGS/

                                    

<body>
    <div class="container"></div>
    <script type="text/javascript">
        var SearchView = Backbone.View.extend({
            el: '.container',
            initialize: function() {
                this.render();
            },
            render: function() {
                $(this.el).html("hello"); //tried both but not working. 
                this.$el.html("hello"); 
            } 
         }); 
         var search_view = new SearchView();
    </script>
</body>