有没有办法用javascript隐藏多个html标签?

时间:2016-11-29 23:07:37

标签: javascript html

我想知道是否有任何简单的方法可以使用Javascript切换HTML元素?我为我的一个项目制作了一堆ascii艺术品,我需要一种有效的方式来展示/隐藏它,而不需要重复相同的一百万次。

这是违规代码的一小部分:

  function dagger(){
  document.getElementById("short").style.display = "none";
  document.getElementById("long").style.display = "none";
  document.getElementById("broad").style.display = "none";
  document.getElementById("choose").style.display = "none";
  /* all the stats and modifiers go here */
}

function short(){
  document.getElementById("dagger").style.display = "none";
  document.getElementById("long").style.display = "none";
  document.getElementById("broad").style.display = "none";
  document.getElementById("choose").style.display = "none";
  /* all the stats and modifiers go here */
}

function long(){
  document.getElementById("short").style.display = "none";
  document.getElementById("dagger").style.display = "none";
  document.getElementById("broad").style.display = "none";
  document.getElementById("choose").style.display = "none";
  /* all the stats and modifiers go here */
}

function broad(){
  document.getElementById("short").style.display = "none";
  document.getElementById("long").style.display = "none";
  document.getElementById("dagger").style.display = "none";
  document.getElementById("choose").style.display = "none";
  /* all the stats and modifiers go here */
}

正如你所看到的,它非常笨重而且巨大。我尝试将id设置为变量并在函数中调用它,如下所示:

var dagger = getElementById("dagger");
var short = getElementById("short");

function dagger(){
  short.style.display = "none";
}

但由于某种原因,这不会起作用。任何想法都将不胜感激。

1 个答案:

答案 0 :(得分:0)

虽然我同意评论者您应该使用课程,但问题的答案是,当您仍然需要致电getElementById时,您正在致电document.getElementById



var long = function() {
  document.getElementById("short").style.display = "none";
  document.getElementById("long").style.display = "none";
  document.getElementById("broad").style.display = "none";
  document.getElementById("choose").style.display = "none";
  /* all the stats and modifiers go here */
}

var short = document.getElementById("short");

var dagger = function() {
	short.style.display = "none";
}

<div id="short">short</div>
<div id="long">long</div>
<div id="broad">broad</div>
<div id="choose">choose</div>

<button onclick="long()">long</button>
<button onclick="dagger()">dagger</button>
&#13;
&#13;
&#13;