使用JavaScript函数参数切换多个元素

时间:2014-07-17 06:12:09

标签: javascript html

我想根据点击的按钮显示/隐藏div。我尝试使用javascript函数的参数进行此操作,但我猜测我做错了所以请帮忙。

这是我的HTML:

<div id="div1">
Content of div1</div>
<div id="div2">
Content of div2</div>

<button id="button" onclick="showhide(x)">Toggle div1</button>

<button id="button" onclick="showhide(y)">Toggle div2</button>

这就是我迄今为止所做的,JS-wise:

<script>
 function showhide(x,y)
 {
       var div x = "div1";
       var div y = "div2";
       var div = document.getElementById(x);
       var div = document.getElementById(y);

if (div.style.display !== "none") {
    div.style.display = "none";
}
else {
    div.style.display = "block";
}
 }
</script>

4 个答案:

答案 0 :(得分:1)

你有一个javascript函数,它有2个参数,在你的HTML中你只发送1。 你能做的是以下几点:

在按钮上的HTML onclick:

<button id="button" onclick="showhide('div1')">Toggle div1</button>
<button id="button" onclick="showhide('div2')">Toggle div2</button>

javascript函数只需要1个参数:

function showhide(divElement)
{

   var div = document.getElementById(divElement);

   if (div.style.display !== "none") {
     div.style.display = "none";
   }
   else {
      div.style.display = "block";
  }
}

答案 1 :(得分:1)

Here is the HTML code :
<div id="div1">
 Content of div1
</div>
<div id="div2">
  Content of div2
</div>

<button id="button" onclick="showhide('div1')">Toggle div1</button>
<button id="button" onclick="showhide('div2')">Toggle div2</button>

Here is the javascript code :

<script type="text/javascript" >
 function showhide(toggleID){
   var toggleDiv = document.getElementById(toggleID);
   if(toggleDiv.style.display != "none"){
    toggleDiv.style.display = 'none';
   }else{
    toggleDiv.style.display = 'block';
   }
 }
</script>

答案 2 :(得分:0)

这是不对的:

var div x = "div1";

你不能有空间:

var div_x = "div1";

你实际上可以删除这两行并保留它:

function showhide(x,y)
 {
       var div = document.getElementById(x);
       var div2 = document.getElementById(y);

       if (div.style.display !== "none") {
           div.style.display = "none";
       }
       else {
           div.style.display = "block";
       }

       if (div2.style.display !== "none") {
           div2.style.display = "none";
       }
       else {
           div2.style.display = "block";
       }
 }

并将其命名为:

showhide("div1", "div2");

答案 3 :(得分:0)

像这样使用:

<button id="button" onclick="showhide(x,'')">Toggle div1</button>

<button id="button" onclick="showhide('',y)">Toggle div2</button>

并改变这一点:

var div = document.getElementById(x);
var div = document.getElementById(y);

对此:

var div = document.getElementById(x && y); //if x returns x else y