如何在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();
答案 0 :(得分:6)
使用tagName
代替el
编辑修复错误的HTML,thanks @muistooshort。刚刚完全删除了<p>
。
var TodoView = Backbone.View.extend({
tagName:'h3',
render: function () {
$('body').append(this.$el.html("fgfdgdfg"));
}
});
var todoView = new TodoView();
todoView.render();
如果您希望视图使用现有DOM元素,则设置el
。设置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();
答案 1 :(得分:2)
您可能不能,因为<p><h3>fgfdgdfg</h3></p>
不是有效的HTML,浏览器通常会尝试更正无效的HTML。
允许的内容
措辞内容
Normal character data或多或少只是没有标记的纯文本,因此<h3>
不会在那里。 Phrasing elements是简单的事情,例如<a>
,<b>
,<img>
,......并且其中也没有<h3>
。
如果您想要一致的结果,则必须修复HTML。然后,一旦你有了有效的HTML,Paul's advice应该完成任务。