繁体   English   中英

如何简洁地编写此javascript以显示/隐藏元素列表?

[英]how to concisely write this javascript to show/hide a list of elements?

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

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";
}

我建议这样:

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类似

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

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

然后,您可以使用JQuery或普通javascript来获取具有“ hideable class”属性的所有元素:

document.getElementsByClassName('hideable')

要么

>$(".hideable")

由于前两个方法将返回一个数组,因此您将不得不遍历该数组并应用适当的style属性。

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

我想为此使用jquery,它使选择DOM元素(尤其是DOM元素集)变得更容易。

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

像这样吗

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

id= "cand" + i;

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

}

我希望这有帮助:

(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" });
   }
})();

尝试一下。它将根据给函数的参数隐藏/显示(按您要求的方式)。

    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]);
}

易于使用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,请忽略我的回答。

(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留给hideCandidates作为练习。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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