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