简体   繁体   English

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

[英]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 hideCandidates类似

You should assign to your html elements a class for example 您应该为html元素分配一个类,例如

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

Then either you use JQuery or plain javascript to get all the elements that have the "hideable class attribute: 然后,您可以使用JQuery或普通javascript来获取具有“ hideable class”属性的所有元素:

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. 由于前两个方法将返回一个数组,因此您将不得不遍历该数组并应用适当的style属性。

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. 并且显然在其中使用一些if语句来处理view_cand元素的显示。

I would look into using jquery for this though, it makes selecting DOM elements (especially sets of DOM elements) a damn site easier. 我想为此使用jquery,它使选择DOM元素(尤其是DOM元素集)变得更容易。

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. 我会在这里为您编写代码,但对于您选择的元素或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: CSS类:

.vissible{ display: block; .vissible {显示:块; } .invissible{ display: none; } .invissible {显示:无; } }

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

Easy to do with jQuery: 易于使用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: 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: CSS:

.candidate { display: none }

Here's a JS fiddle: http://jsfiddle.net/vbh5T/ 这是一个JS小提琴: http : //jsfiddle.net/vbh5T/

If you don't want to use jQuery then please ignore my answer. 如果您不想使用jQuery,请忽略我的回答。

(1) First of all, doing these kinds of lookups is best done with jquery. (1)首先,最好使用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. 这很重要,因为按ID查找将扫描整个文档树。 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. (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>

I leave the corresponding hideCandidates as an exercise for the reader. 我将相应的hideCandidates留给hideCandidates作为练习。

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

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