改进代码"内容转换器"

时间:2015-07-28 17:57:54

标签: javascript html

我试图改进我的名字,因为我称之为#34; contenthandler"。它的作用是当我点击不同的按钮时它会改变不同的文章。我很高兴它是如何工作的,但我觉得这不是最好的做法,我想要一些关于如何缩短它或者使用任何其他方法来做到这一点的建议。

我现在对任何jQuery或其他库不感兴趣。

document.addEventListener("click", function(e){
  var article = document.getElementsByClassName("test"); // Article becomes an array.
  var buttonClick = e.target.className;
  switch (buttonClick){
    case "one":
      test(article);
      article[0].style.display = "";
      break; 
    case "two":
      test(article);
      article[1].style.display = "";
      break; 
    case "three":
      test(article);
      article[2].style.display = "";
      break;
  }
  function test(article){
    for (var i = 0; i < article.length; i++){
      article[i].style.display = "none";
    }
  }
});
//html
<ul>
  <li class="buttonNav"><h2 class="one">Show 1</h2></li>
  <li class="buttonNav"><h2 class="two">Show 2</h2></li>
  <li class="buttonNav"><h2 class="three">Show 3</h2></li>
</ul>
    <article class="test" style="display: none">1</article>
    <article class="test" style="display: none">2</article>
    <article class="test" style="display: none">3</article>

[编辑]

我从我得到的答案重新制作了剧本,但我对它进行了一些小改动并使其变得动态,所以我不需要硬编码&#34;菜单&#34;在脚本文件中。

var getClassName = document.querySelectorAll("h2");
var classNamesArray = [];

for (var i = 0; i < getClassName.length; i++){
    classNamesArray.push(getClassName[i].className.toString());
};

document.addEventListener("click", function (e) {
    var article = document.getElementsByClassName("test"); // Article becomes an array.
    var buttonClick = e.target.className,
        // Maintain list of class names in an order
        validClassNames = classNamesArray,
        index = -1;
    for (var i = 0; i < validClassNames.length; i++) {
        if (buttonClick === validClassNames[i]) {
            index = i;
            break;
        }
    }
    if (index >= 0) {
        test(article);
        article[index].style.display = "";
    }
});

function test(article) {
    for (var i = 0; i < article.length; i++) {
        article[i].style.display = "none";
    }
}

1 个答案:

答案 0 :(得分:1)

我能想到的一种方法是

document.addEventListener("click", function (e) {
    var article = document.getElementsByClassName("test"); // Article becomes an array.
    var buttonClick = e.target.className,
        // Maintain list of class names in an order
        validClassNames = ["one", "two", "three"],
        index = -1;
    for (var i = 0; i < validClassNames.length; i++) {
        if (buttonClick === validClassNames[i]) {
            index = i;
            break;
        }
    }
    if (index >= 0) {
        test(article);
        article[index].style.display = "";
    }
});

function test(article) {
    for (var i = 0; i < article.length; i++) {
        article[i].style.display = "none";
    }
}

还将函数定义移动到事件处理程序之外。

<强> Fiddle