Home >Web Front-end >JS Tutorial >How to implement the tab page function using js and jquery respectively

How to implement the tab page function using js and jquery respectively

高洛峰
高洛峰Original
2016-12-06 14:39:161493browse

The example in this article describes how js and jquery implement the tab page function respectively. Share it with everyone for your reference, the details are as follows:

First list the styles and html tags

<style type="text/css">
    *{margin: 0;padding: 0;}
    #myul li {list-style: none; float: left; border: 1px solid #ddd; width: 100px; height: 20px; text-align: center; line-height: 20px;}
    #container div{display: none; width: 303px; height: 300px; border: 1px solid #ddd; }
    #container .ssd{display: block;}
    .ssl{background: #abcdef;}
</style>
</head>
<body>
  <div id="tab">
    <ul id="myul">
      <li class="ssl">1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <div id="container">
      <div class="ssd">woshi1</div>
      <div>woshi2</div>
      <div>woshi3</div>
    </div>
  </div>
</body>

Then the native js code to implement the tab tag

<script type="text/javascript">
var ul = document.getElementById(&#39;myul&#39;);
var li = ul.getElementsByTagName(&#39;li&#39;);
var con = document.getElementById(&#39;container&#39;);
var div = con.getElementsByTagName(&#39;div&#39;);
var len = li.length;
for (var i = 0; i < len; i++) {
li[i].index = i;
li[i].onclick=choose;
li[i].onmouseover = choose;
};
function choose(){
for(var j = 0; j < len; j++) {
    li[j].className = &#39;&#39;;
    div[j].style.display = &#39;none&#39;;
  }
  this.className = &#39;ssl&#39;;
  div[this.index].style.display=&#39;block&#39;;
}
</script>

Then we use jquery to implement the code as follows

$(&#39;#myul li&#39;).click(choose);
$(&#39;#myul li&#39;).hover(choose);
function choose(){
  $(this).addClass(&#39;ssl&#39;).siblings().removeClass(&#39;ssl&#39;);
  $(&#39;#container div&#39;).eq($(this).index()).show().siblings().hide();
}

In fact, the function can be simplified:

function choose(){
  $(this).addClass(&#39;ssl&#39;).siblings().removeClass(&#39;ssl&#39;).parent().next().children().eq($(this).index()).show().siblings().hide();
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn