本来这节是想讲讲用AJAX获取选项卡的内容,但是在编写过程中,发现前两天写的第三节,动态创建和删除选项卡功能里有BUG,于是动手将BUG修正。
改完后,一时兴起,决定把动态创建删除功能再次增强,现在不仅能创建静态内容选项卡,还能用AJAX获取内容并创建选项卡。
另外新加了判断,如果选项卡已经创建,那么再点击新建不会再次创建新的选项卡,而是显示已经创建了的选项卡。
addSection函数包括三个参数,第一个是选项标签的文本,第二个是选项内容的文本,如果使用AJAX获取内容,就是url地址,第三个为可选的options参数,包括有插入的位置,删除功能标签,是否使用AJAX,创建选项卡的ID。
而通过选项卡的ID,在DOM中检索是否已经存在,已经存在的话,就显示相应的选项卡,没有则创建一个。
目前这个代码原型已经基本实现了选项卡式邮箱所需要的功能,可以在此基础上继续扩展实现更强大的功能。
AJAX动态新建选项卡示例
本节完整代码如下:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1 /**
2 * implement two methods to Tabs class: addSection & removeSection
3 */
4 Tabs.implement({
5 addSection:function(newTabHtml,newSectionHtml,options){
6 var options =$merge({
7 pos:null,
8 del:'tabDel',
9 isAjax:false
10 },options);
11 var isCreated = $(options.id);
12 if(isCreated){
13 this.toggleSection(this.tabs.indexOf(isCreated));
14 return;
15 }
16 var length = this.sectionsLength;
17 var pos = $pick(options.pos, length).limit(0, length);
18
19 pos2 = pos==length?pos-1:pos;
20 var oldTab = this.tabs[pos2];
21 var oldSection = this.sections[pos2];
22
23 var posMethod = pos == length ? 'after':'before';
24 var newTab = oldTab.clone().set({'html':newTabHtml,'id':options.id}).inject(oldTab,posMethod);
25 var newSection = oldSection.clone().setStyle('display','none').inject(oldSection,posMethod);
26 if(options.isAjax){
27 var request = new Request.HTML(
28 $merge(this.options.requestOptions,{
29 method:'get',
30 update:newSection,
31 url:newSectionHtml
32 })
33 )
34 request.send();
35 }else{
36 newSection.set('html',newSectionHtml)
37 }
38
39 this.tabs.splice(pos,0,newTab)
40 this.sections.splice(pos,0,newSection)
41 this.sectionsLength++;
42
43 if(pos<=this.current){
44 this.current++;
45 }
46
47 var delA= newTab.getElement('a.'+options.del);
48 if (delA){
49 delA.addEvent('click',this.removeSection.bindWithEvent(this,[newTab,delA]));
50 }
51
52 newTab.addEvent(this.options.mouseEvent,this.tabEvent.bindWithEvent(this,newTab));
53 this.toggleSection(pos);
54
55 this.fireEvent('onAdd',[newTab,newSection]);
56 },
57
58 removeSection:function(e,tab,delA){
59 e.stop();
60 delA.removeEvents();
61 var index = this.tabs.indexOf(tab);
62
63 this.tabs.splice(index,1);
64 var section = this.sections.splice(index,1)[0];
65 this.sectionsLength--;
66
67 tab.removeEvents();
68 tab.destroy();
69 section.destroy();
70
71 if (this.current == index) {
72 this.current = (index - 1).limit(0, this.sectionsLength);
73 }
74 else if(this.current>index) {
75 this.current--;
76 this.current = this.current.limit(0, this.sectionsLength);
77 }
78 this.showSection(this.current);
79 this.fireEvent('onRemove',index);
80 }
81 });