什么';将click listener添加到我的javascript选项卡栏的最佳方法是什么?
我计划用JavaScript实现一个选项卡栏模块 我想在每次加载页面时创建一个选项卡栏,然后在其中放入两个选项卡 问题是,将单击事件添加到我的选项卡的最佳方式是什么 这是我的密码:什么';将click listener添加到我的javascript选项卡栏的最佳方法是什么?,javascript,javascript-events,Javascript,Javascript Events,我计划用JavaScript实现一个选项卡栏模块 我想在每次加载页面时创建一个选项卡栏,然后在其中放入两个选项卡 问题是,将单击事件添加到我的选项卡的最佳方式是什么 这是我的密码: // A tab in tab bar. Tab = function(titleID, contentID) { this.title = document.getElementById(titleID); this.content = document.getElementById(content
// 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"));
}
//选项卡栏中的选项卡。
Tab=函数(titleID,contentID){
this.title=document.getElementById(titleID);
this.content=document.getElementById(contentID);
}
Tab.prototype.show=函数(){
this.title.className=“title bg active”;
}
Tab.prototype.hide=函数(){
this.title.className=“”;
}
//选项卡栏包含多个选项卡。
TabBar=函数(){
this.tabs=[];
}
TabBar.prototype.add=函数(选项卡){
//TODO添加单击“将侦听器添加到”选项卡
这个.tabs.push(tab);
}
TabBar.prototype.open=函数(选项卡){
对于(var i=0;i
我真的不想使用jQuery或任何其他库,谢谢
编辑:我还需要通知其他选项卡关闭,如何在
onclick
中关闭?我认为选项卡应该包含一个tabbar
,但是如何在选项卡构造函数中添加this.title.onclick=this.onclick
,然后在原型中定义onclick:
Tab.prototype.onclick = function(event) {
// handle click
// 'this' will hold the clicked element
}
考虑到您的更新,这可能会起作用:
TabBar.prototype.add = function(tab) {
var bar = this;
tab.title.onclick = (function(clickedTab){
return function() {
// Hide all tabs
for(var i=0; i<bar.tabs.length; i++) {
bar.tabs[i].hide();
}
// Show clicked tab
clickedTab.show();
}
}(tab));
this.tabs.push(tab);
}
TabBar.prototype.add=函数(tab){
var bar=此;
tab.title.onclick=(函数(单击选项卡){
返回函数(){
//隐藏所有选项卡
对于(var i=0;iThanks!这真的很有帮助。