使用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();
您设置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);
如果你的 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();