问题描述
||
为什么在骨干网.js中重新渲染视图时会渲染额外的div
Backbone.View.extend({
template :_.template(
\'<li id=\"user-<%=user.username%>\" class=\"pp-entry group\">\'+
\'<img src=\"i/pp-pic-1.png\" class=\"pp-pic\" alt=\"\" />\'+
\'<span class=\"whisper-mode-on hide\" title=\"Whisper mode on\"></span>\'+
\'<h6 class=\"pp-name\"><%=user.firstname%> <%if(user.lastname!=\"null\"){%><%=user.lastname%><%}%></h6>\'+
\'<p id=\"chat-<%=user.username%>\"class=\"pp-msg\"></p>\'+
\'</li>\'),initialize: function() {
_.bindAll(this,\'render\',\'close\');
this.model.bind(\'change\',this.render);
this.model.view = this;
},// Re-render the contents of the User item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
$(\"#participant-window\").prepend(this.el);
}
});
当它得到它呈现如下:
<ul id=\"participant-window\" class=\"scroll-pane\" style=\"overflow: hidden; padding: 0px; width: 357px;\">
<div>
<li id=\"user-ashutosh\" class=\"pp-entry group\" style=\"cursor: default;\">
<img class=\"pp-pic\" alt=\"\" src=\"i/pp-pic-1.png\">
<span class=\"whisper-mode-on hide\" title=\"Whisper mode on\"></span>
<h6 class=\"pp-name\">Ashutosh </h6>
<p id=\"chat-ashutosh\" class=\"pp-msg\"></p>
</li>
</div>
</ul>
为什么将li插入div中,应该如何停止呢?
解决方法
在这一行:
$(this.el).html(this.template(this.model.toJSON()));
...您将ѭ3的内容设置为模板输出。如果以某种方式已经将el
成员变量初始化为现有的div
元素,则只需更改其内容,然后追加到#participant-window
即可。
也许尝试:
this.el = $(this.template(this.model.toJSON())));
, 除非您重写它,否则Backbone.View的el
属性将初始化为div标签。
因此,“ 9”将把评估后的模板放入div标签。
从您的代码示例中,您看起来实际上想要将this.el
设置为$(\"ul#participant-window\")
。那么您在渲染中要做的就是
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
}