【问题标题】:how to concisely write this javascript to show/hide a list of elements?如何简洁地编写这个 javascript 来显示/隐藏元素列表?
【发布时间】:2012-02-20 13:13:09
【问题描述】:

如何在循环中编写这种类型的代码?其实我不想一遍又一遍地写同一行,他们有什么办法压缩这段代码吗?我们可以循环编写这段代码吗?

function showCandidates()
{document.getElementById("cand9").style.display="block";
document.getElementById("cand10").style.display="block";
document.getElementById("cand11").style.display="block";
document.getElementById("cand12").style.display="block";
document.getElementById("cand13").style.display="block";
document.getElementById("cand14").style.display="block";
document.getElementById("cand15").style.display="block";
document.getElementById("hide_cand").style.display="block";
document.getElementById("view_cand").style.display="none";
}

function hideCandidates()
{document.getElementById("cand9").style.display="none";
document.getElementById("cand10").style.display="none";
document.getElementById("cand11").style.display="none";
document.getElementById("cand12").style.display="none";
document.getElementById("cand13").style.display="none";
document.getElementById("cand14").style.display="none";
document.getElementById("cand15").style.display="none";
document.getElementById("hide_cand").style.display="none";
document.getElementById("view_cand").style.display="block";
}

【问题讨论】:

  • for(var i=9;i
  • 我很想自己提出类似的东西 mshsayem 但这对于 rashtra 来说并不完全可扩展,例如,如果他要添加另一个“cand16”元素。而且它不处理 'hide_cand' 和 'view_cand' 元素。
  • 了解arraysCSS classes

标签: css for-loop show-hide javascript


【解决方案1】:

我建议这样:

var show_ids = ["cand9", "cand10", "cand11"] // ... and so on

funciton showCandidates() {
    for (var index in show_ids) {
        var id = show_ids[index];
        document.getElementById(id).style.display="none";
    }
}

hideCandidates 类似

【讨论】:

    【解决方案2】:

    您应该为您的 html 元素分配一个类,例如

    <div class="hideable" >content </div>

    然后你可以使用 JQuery 或纯 javascript 来获取所有具有“可隐藏类属性:”的元素:

    document.getElementsByClassName('hideable')
    

    >$(".hideable")
    

    由于您之前的两个方法将返回一个数组,因此您必须遍历该数组并应用适当的样式属性。

    【讨论】:

      【解决方案3】:

      首先,这可以全部封装到一个函数中。该函数可以接受一个参数来分配给显示属性。并且显然在其中使用了一些 if 语句来处理 view_cand 元素的显示。

      不过,我会考虑使用 jquery,它使选择 DOM 元素(尤其是 DOM 元素集)变得更容易。

      我会在这里为您编写代码,但我对您选择的元素或 DOM 的结构一无所知。

      【讨论】:

        【解决方案4】:

        这样的?

        for(i=0;i<candNumber;i++){

        id= "cand" + i;

        document.getElementById(id).style.display="block";

        }

        【讨论】:

          【解决方案5】:

          Try this 。它会通过给函数的参数隐藏/显示(您要求的方式)。

              setVisibilityByClass("visible"/"invisible") - shows/hides by changing class
              setVisibility("block"/"none") - shows/hides by changing styles directly
          CHOOSE ONLY ONE.
          

          css 类:

          .vissible{ 显示:块; } .invissible{ 显示:无; }

          js函数:

          function setVisibility(val) {
              var not = new Array;
              not["none"] = "block";
              not["block"] = "none";
              for (i = 9; i <= 15; i++){
                  document.getElementById("cand" + i).style.display = val;
              }
              document.getElementById("hide_cand").style.display = val;
              document.getElementById("view_cand").style.display = not[val];
          }
          function setVisibilityByClass(val) {
              var not = new Array;
              not["invissible"] = "vissible";
              not["vissible"] = "invissible";
              for (i = 9; i <= 15; i++){
                  document.getElementById("cand" + i).setAttribute("class", val);
              }
              document.getElementById("hide_cand").setAttribute("class", val);
              document.getElementById("view_cand").setAttribute("class", not[val]);
          }
          

          【讨论】:

            【解决方案6】:

            我希望这会有所帮助:

            (function() {
              "use strict";
            
              var candidates = {
                idx: 0,
                getElement: function(id) { return document.getElementById(id); },
            
                toggle: function(elmnts, obj) {
                  var idx = candidates.idx,
                      getElement = function(id) { return candidates.getElement(id); };
            
                  if (elmnts.length) {
                    while ( idx < elmnts.length ) {
                      getElement(elmnts[idx]).style.display = obj.display;
                      idx++;
                    }
                  }
                }
              };
            
              var idsToHide = [
                "cand9", "cand10", "cand11", "cand12",
                "cand13", "cand14", "cand15", "hide_cand"
              ];
              var idsToShow = [
                "cand9", "cand10", "cand11", "cand12",
                "cand13", "cand14", "cand15", "hide_cand"
              ];
            
              function showCandidates() {
                  candidates.toggle(idsToShow, {
                      display: "block" 
                  });
                  candidates.toggle(["view_cand"], { display: "none" });
              }
              function hideCandidates() {
                  candidates.toggle(idsToHide, {
                      display: "none"
                  });
                  candidates.toggle(["view_cand"], { display: "block" });
               }
            })();
            

            【讨论】:

              【解决方案7】:

              用 jQuery 轻松实现:

              $(document).ready(function(){
                  $("#candidates").toggle(function (){
                      $(this).text('Hide Candidates');
                      $.each($('.candidate'), function() {
                          $(this).show();
                      });
                  }, function() {
                      $(this).text('Show Candidates');
                      $.each($('.candidate'), function() {
                          $(this).hide();
                      });
                  });
              });
              

              HTML:

              <a href="#" id="candidates">Show Candidates</a>
              
              <div class='candidate' id='1'>
                  <h1>Hello</h1>
              </div>
              <div class='candidate' id='2'>
                  <h1>Hello</h1>
              </div>
              <div class='candidate' id='3'>
                  <h1>Hello</h1>
              </div>
              

              CSS:

              .candidate { display: none }
              

              这是一个 JS 小提琴:http://jsfiddle.net/vbh5T/

              如果您不想使用 jQuery,请忽略我的回答。

              【讨论】:

              • 请注意,这将在每次调用处理程序时遍历整个 DOM。
              • 仍然比你的解决方案更干净。
              • 并非如此,尤其是如果您关心性能。
              • 我们正在显示和隐藏divs。我们不是在做量子力学计算。我说答案更简洁,而不是更高效(反正他不会注意到)
              • 在任何客观标准上,您的解决方案既不干净也不更好;恰恰相反。性能特征在任何具有合理数量元素的页面上都很重要。
              【解决方案8】:

              (1) 首先,最好使用 jquery 来完成这些类型的查找。除了更容易(参见下面的代码)之外,它还允许您预先计算要操作的元素集。这很重要,因为按 ID 查找会扫描整个文档树。因此,页面中的元素越多,重新计算要操作的元素集的速度就越慢。

              (2) 与其设置单独的属性,不如使用css类。

              <style>
               .invisible {display:none !important;}
              </style>
              
              <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
              
              <script type="text/javascript" charset="utf-8"> // <![CDATA[
              
              
              $(document).ready(function(){  
              
              
              var hide = function(i) {i.addClass('invisible');};
              var show = function(i) {i.removeClass('invisible');};
              
              
              var candidates = $("#cand9, #cand10 /* etc. [...] */");
              /* or, if you rejig this to set a class on all candidate elements:
              var candidates = $(".candidate"); */
              
              var hide_cand = $("#hide_cand");
              var view_cand = $("#view_cand");
              function showCandidates()
              {
                  show(candidates);
                  show(view_cand);
                  hide(hide_cand);
              }
              
              });  
              // ]]>
              </script>
              

              我将相应的hideCandidates留给读者作为练习。

              【讨论】:

              • 你知道如果他们都有相同的类名,他可以通过使用选择器 $(".candidate") 在 jquery 中循环它们,对吧?
              • @Flukey:当然,但这不是被问到的问题。
              • 是的,是的,他可以保留他列出的相同 id,但是在这些元素上使用一个类,然后在 jquery 中进行一个类选择来显示和隐藏(就像我的回答一样)在你的方法,每次他添加一个新的候选人时,他都必须更新JS中的候选人变量。效率不高。
              • @Flukey:那么,您对这段代码的批评是它包含两种稍微不同的定义函数的语法?你是软件工程天才。
              • @Flukey:还有喜剧演员,除非你不知道什么是讽刺。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-10-12
              • 2015-01-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-06-14
              相关资源
              最近更新 更多