简体   繁体   中英

Condensing javascript

I'm not much of a Javascript programmer at all, but I have figured out a way to create a tabbed area (ie, clicking a tab shows a different DIVs content), but my code seems awfully bulky. Was wondering if anyone could enlighten me on how to condense it somewhat.

Here's the HTML:

<aside id="sb-popular">
  <p class="sb-popular-nav">
    <a id="sbpt1" class="current" href="javascript:showdiv('sbp-latest'); hidediv('sbp-commented'); hidediv('sbp-popular'); hidediv('sbp-views'); tabset('sbpt1'); taboff('sbpt2'); taboff('sbpt3'); taboff('sbpt4');">Latest</a>
    <a id="sbpt2" href="javascript:showdiv('sbp-commented'); hidediv('sbp-latest'); hidediv('sbp-popular'); hidediv('sbp-views'); tabset('sbpt2'); taboff('sbpt1'); taboff('sbpt3'); taboff('sbpt4');">Commented</a>
    <a id="sbpt3" href="javascript:showdiv('sbp-popular'); hidediv('sbp-commented'); hidediv('sbp-latest'); hidediv('sbp-views'); tabset('sbpt3'); taboff('sbpt1'); taboff('sbpt2'); taboff('sbpt4');">Popular</a>
    <a id="sbpt4" href="javascript:showdiv('sbp-views'); hidediv('sbp-commented'); hidediv('sbp-popular'); hidediv('sbp-latest'); tabset('sbpt4'); taboff('sbpt2'); taboff('sbpt3'); taboff('sbpt1');">Views</a>
  </p>
  <div id="sbp-latest">
    Content here
  </div>
  <div id="sbp-commented">
    Content here
  </div>
  <div id="sbp-popular">
    Content here
  </div>
  <div id="sbp-views">
    Content here
  </div>
</aside>

As you can see the javascript there is a bit unwieldy. Here's my JS.

function hidediv(d) { document.getElementById(d).style.display = "none"; }
function showdiv(d) { document.getElementById(d).style.display = "block"; }
function tabset(d) { document.getElementById(d).style.color = "white";}
function taboff(d) { document.getElementById(d).style.color = "black";}

1) It is not considered good practice to call javascript in the href. Instead use onclick and return false:

function showDiv() {
  .
  .
  .
  return false
}

using

<a href="#" onclick="return showDiv('....')"

2) you can assign the onclick in the head using

window.onload=function() {
  var links = document.getElementById('sb-popular').document.getElementsByTagName('a');
  for (...)  {
    links[i].onclick=function() {
      ..
      ..
      ..
    }
  }
}

first you need to consider making an init function that will hide all tabs

and show the default tab.

then in each show function you need to get the showed tab hide it then show

the tab you clicked on.

your start is good keep it coming man !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM