在现有“添加”选项卡之前添加动态引导选项卡
问题描述:
我正在与backbone.js一起工作,并且有关于<ul>
元素的以下listView
元素和用于动态<li>
元素的单独tabView
。在listView
的渲染方法中,我将创建一个新的tabView
并将el
附加到listView
el
。在现有“添加”选项卡之前添加动态引导选项卡
var listView = Backbone.View.extend({
//<ul> element for tabs
el: '.nav-tabs',
render: function(model) {
var tabView = new TabView({ model: model });
tabView.render();
$(this.el).append(tabView.el);
}
var TabView = Backbone.View.extend({
//create <li> element to hold each tab
tagName: "li",
className: "currentTab ",
render() {
var html = this.template(this.model.attributes);
$(this.el).append(html);
//creates new div for tab content
var tabContent = new TabContentView({ model: this.model });
tabContent.render();
}
这是罚款和按预期工作。
要动态添加新选项卡,我在开始时有一个li
项目,因此当用户单击该li
项目时,只会发生新的选项卡创建。
现在我需要的是在li
+元素之前添加新创建的选项卡。目前所有新标签只有在this
+元素后才会添加。
以下是<ul>
标签的html供参考。
<div id="test">
<ul class="nav nav-tabs ">
<li><a href="#" class="add-newTab">+</a></li>
</ul>
</div>
我尝试了改变listView
渲染方法如下图所示,但不起作用。相反,它只是在(+)li
元素本身之上添加新选项卡。
tabView.render();
$(this.el).find(".add-newTab").before(tabView.el);
任何想法如何做到这一点?
答
jQuery提供prepend
或before
方法取决于你真正想要什么。
prepend
<ul class="nav nav-tabs ">
<li>prepending adds element here</li>
<li></li>
<li class="plus"><a href="#" class="add-newTab">+</a></li>
</ul>
before
<ul class="nav nav-tabs ">
<li></li>
<li>before adds element here when used on $('.plus')</li>
<li class="plus"><a href="#" class="add-newTab">+</a></li>
</ul>
这里是一个简单的实现你的清单,选项卡:
var TabView = Backbone.View.extend({
//create <li> element to hold each tab
tagName: "li",
className: "currentTab", // why? all tabs will have "currentTab"
initialize: function() {
//creates new div for tab content
this.tabContent = new TabContentView({
model: this.model
});
},
// render should only renders, and should be idempotent.
render: function() {
this.$el.empty().append(tabContent.render().el);
// returning "this" is the default in Backbone, which enables
// chaining method calls.
return this;
}
});
var ListView = Backbone.View.extend({
//<ul> element for tabs
el: '.nav-tabs',
template: '<li class="plus"><a href="#" class="add-newTab">+</a></li>',
events: {
"click .add-newTab": "onAddTab",
},
render: function() {
this.$el.empty().append(this.template);
// cache the '+' li element.
this.$plus = this.$('.plus');
return this;
},
onAddTab: function(e) {
var tabView = new TabView({ model: this.model });
// the magic happens here.
// if you want the tab at the beginning of the ul:
this.$el.prepend(tabView.render().el);
// or if you want it at the end, but before the + :
this.$plus.before(tabView.render().el);
},
});
您不需要使用全局jQuery来选择元素,Backbone视图有自己的预定义范围并可以通过this.$el
访问的元素。
如果你真的需要找到里面的视图的el
的元素,则可以使用this.$('.element-you-want')
这是一个快捷方式可以选择:
$(this.el).find('.element-you-want')