简体   繁体   中英

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

How to write this type of code in loop? Actually I don't want to write the same same line again and again, Is their any way to compress this code? can we write this code in loop?

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

I suggest this way:

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

similar for hideCandidates

You should assign to your html elements a class for example

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

Then either you use JQuery or plain javascript to get all the elements that have the "hideable class attribute:

document.getElementsByClassName('hideable')

or

>$(".hideable")

Since your the two previous methods will return an array, you will have to loop through the array and apply the appropriate style attribute.

Firstly, this can be all encapsulated into one function. The function can take a parameter to assign to the display property. And obviously use some if statement in there to deal with the view_cand elements' display.

I would look into using jquery for this though, it makes selecting DOM elements (especially sets of DOM elements) a damn site easier.

I'd write the code for you here but I don't know anything about the elements you're selecting or the structure to your DOM.

像这样吗

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

id= "cand" + i;

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

}

I hope this helps:

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

Try this .It'll hide/show ( the wayas you requested) by parameter given to function.

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

css classes:

.vissible{ display: block; } .invissible{ display: none; }

Js functions:

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

Easy to do with 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 }

Here's a JS fiddle: http://jsfiddle.net/vbh5T/

If you don't want to use jQuery then please ignore my answer.

(1) First of all, doing these kinds of lookups is best done with jquery. Apart from being easier (see code below), it also allows you pre-calculate the set of elements to act on. This matters, because lookups by ID scan the whole document tree. Accordingly, the more elements in the page, the slower it is to recalculate the set of elements to act on.

(2) Rather than setting individual properties, it is much better to use a css class.

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

I leave the corresponding hideCandidates as an exercise for the reader.

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