JavaScript面向对象实现选项卡切换功能详解

作者:纸飞机

时间:2026-10-21

浏览:159

本文详细介绍如何将面向过程的JavaScript选项卡代码改写为面向对象形式。通过封装构造函数、将全局变量转为属性、函数转为方法,并处理window.onload中的变量作用域问题,实现更规范的Tab切换效果。

文章目录

面向对象选项卡实现概述

本文通过具体实例,展示了如何使用JavaScript面向对象技术来实现选项卡切换效果,供读者参考学习。

核心思路在于将原本面向过程的代码逻辑,重构为面向对象的结构。

HTML结构与样式基础


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 input {background:#CCC;}
#div1 .active {background:yellow;}
#div1 div {width:200px; height:200px; background:#CCC; display:none;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function ()
{
  var oDiv=document.getElementById('div1');
  var aBtn=oDiv.getElementsByTagName('input');
  var aDiv=oDiv.getElementsByTagName('div');
  var i=0;
  for(i=0;i<aBtn.length;i++)
  {
    aBtn[i].index=i;
    aBtn[i].onclick=function ()
    {
      for(i=0;i<aBtn.length;i++)
      {
        aBtn[i].className='';
        aDiv[i].style.display='none';
      }
      this.className='active';
      aDiv[this.index].style.display='block';
    };
  }
};
</script>
</head>
<body>
<div id="div1">
  <input class="active" type="button" value="教育" />
  <input type="button" value="财经" />
  <input type="button" value="aaa" />
  <div style="display:block;">1asdfasdfds</div>
  <div>2xzcvxzcv</div>
  <div>5332342345</div>
</div>
</body>
</html>

重构注意事项

在重构过程中,需要注意以下关键事项:

1.前提:所有代码必须包含在window.onload里面 2.去掉函数嵌套(window.onload里面嵌套的函数拎到window.onload外面去) 3.不能有函数嵌套,但可以有全局变量(比如onclick函数拎出去后,aBtn是window.onload函数里的私有变量,onclick函数不能用)

具体的重构步骤如下:

第一步,通过window.onload初始化整个程序,并调用构造函数来初始化对象。第二步,将原有的全局变量转换为对象的属性。第三步,将独立的函数封装为对象的方法。

面向对象代码实现


window.onload=function(){
  var oTab=new TabSwitch("div1");
}
function TabSwitch(id)
{
  var oDiv=document.getElementById(id);
  this.aBtn=oDiv.getElementsByTagName('input');
  this.aDiv=oDiv.getElementsByTagName('div');
  var i=0;
  var _this=this;     //this是new出来的对象,即oTab
  for(i=0;i<this.aBtn.length;i++)
  {
    this.aBtn[i].index=i;
    this.aBtn[i].onclick=function(){
      _this.tab(this);  //通过参数的形式,将被点击的按钮传到下面去
    };
  }
};
TabSwitch.prototype.tab=function(oBtn){
  for(i=0;i<this.aBtn.length;i++)
  {
    this.aBtn[i].className='';
    this.aDiv[i].style.display='none';
  }
  oBtn.className='active';  //要被点击的按钮改变,而不是new出来的对象,所以这里不用this
  this.aDiv[oBtn.index].style.display='block';
}

相关资源推荐

如果您对JavaScript其他技术感兴趣,可参考本站相关教程,包括《javascript面向对象入门教程》、《JavaScript切换特效与技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》。

希望上述内容能对您的JavaScript程序设计提供有益帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章