我打算在 JavaScript 中实现一个标签栏模块。
我想在每次加载页面时创建一个TabBar ,然后将两个Tab放入其中。
问题是,将点击事件添加到我的标签的最佳方式是什么?
这是我的代码:
// A tab in tab bar.
Tab = function(titleID, contentID) {
this.title = document.getElementById(titleID);
this.content = document.getElementById(contentID);
}
Tab.prototype.show = function() {
this.title.className = "title-bg-active";
}
Tab.prototype.hide = function() {
this.title.className = "";
}
// Tab bar contains several tabs.
TabBar = function() {
this.tabs = [];
}
TabBar.prototype.add = function(tab) {
// TODO add click listener to tab
this.tabs.push(tab);
}
TabBar.prototype.open = function(tab) {
for(var i = 0; i < this.tabs.length; i++) {
if(tab.title == this.tabs[i].title) {
tab.show();
}else{
tab.hide();
}
}
}
window.onload = function(){
tb = new TabBar();
tb.add(new Tab("famous", "famous-content"));
tb.add(new Tab("recently", "recently-content"));
}
我真的不想使用 jQuery 或任何其他库,谢谢!
编辑:
我还需要通知其他选项卡关闭,我该怎么做onclick
?我认为标签应该持有 a tabbar
,但是如何?