view render - backbone.js

Hel*_*rld 1 javascript backbone.js

如何在backbone.js结果中获得此结果 <p><h3>fgfdgdfg</h3></p>

var TodoView = Backbone.View.extend({
    el:'p',
    render: function () {
        $('body').append(this.$el.html("<h3>fgfdgdfg</h3>"));
    }
});

var todoView = new TodoView();
todoView.render();
Run Code Online (Sandbox Code Playgroud)

Pau*_*cke 6

tagName而不是el.
编辑修复坏的HTML,谢谢@muistooshort.刚刚删除<p>了.

var TodoView = Backbone.View.extend({

    tagName:'h3',
    render: function () {
        $('body').append(this.$el.html("fgfdgdfg"));
    }

});

var todoView = new TodoView();
todoView.render();
Run Code Online (Sandbox Code Playgroud)

您设置el是否存在您希望视图使用的现有DOM元素.设置tagName告诉Backbone为视图的根生成'h3'元素.

你也可以这样做(我更喜欢这种方式;避免设置'el'):

var TodoView = Backbone.View.extend({

    tagName:'h3',
    render: function () {
        this.$el.html("fgfdgdfg");
        return this;
    }

});

// view is more reusable now, since it doesn't have the 'body' part in render.
// So, another instance could be rendered and added to the page somewhere else.
var todoView = new TodoView();
$('body').append(todoView.render().el);
var todoView2 = new TodoView();
$('body').append(todoView2.render().el);
Run Code Online (Sandbox Code Playgroud)

如果你的html已经有了想要用于视图的'h3'元素,你可以这样做:

// assuming this html on the page already:
// <body><h3></h3></body>
var TodoView = Backbone.View.extend({

    // setting 'el' tells backbone to use the existing <h3>.
    // You probably would want to use an id rather than 'h3' though.
    el:'h3',
    render: function () {
        this.$el.html("fgfdgdfg");
        return this;
    }

});

var todoView = new TodoView();
todoView.render();
Run Code Online (Sandbox Code Playgroud)