简体   繁体   中英

Why does three functions with same name works only once?

Does anyone know why this is?

I'm trying to make it possible to hide any of the three areas by clicking on the respective button.

Here's my code:

<div id="prod">Prod

  <button type="button" onclick="myFunction()" class="prodButton">Hide</button>

  <script>
    function myFunction() {
      document.getElementById("prod").style.visibility = "hidden";
    }
  </script>
</div>
<div id="test">Test

  <button type="button" onclick="myFunction()" class="testButton">Hide</button>

  <script>
    function myFunction() {
      document.getElementById("test").style.visibility = "hidden";
    }
  </script>
</div>
<div id="dev">Dev

  <button type="button" onclick="myFunction()" class="devButton">Hide</button>

  <script>
    function myFunction() {
      document.getElementById("test").style.visibility = "hidden";
    }
  </script>
</div>

Every time you do this:

function myFunction() {

You are apparently redefining the function (killing the old function and creating a new one, so that the last one only wins ). You need to make it in such a way that it accepts an argument and based on that it should do something. You are misusing or not getting the concept of functions.

Ultimately your function should look like:

function myFunction(element) {
  document.getElementById(element).style.visibility = "hidden";
}

Defined just once and it should be called multiple times, like below:

myFunction("prod");
myFunction("test");
myFunction("dev");

Full Code

<script>
  function myFunction(element) {
    document.getElementById(element).style.visibility = "hidden";
  }
</script>
<div id="prod">Prod
  <button type="button" onclick="myFunction(\"prod\")" class="prodButton">Hide</button>
</div>
<div id="test">Test
  <button type="button" onclick="myFunction(\"test\")" class="testButton">Hide</button>
</div>
<div id="dev">Dev
  <button type="button" onclick="myFunction(\"dev\")" class="devButton">Hide</button>
</div>

If you really want to just test out some code quickly, then you can write inline javascript code like below. But this should not be written as production code.

    <div id="prod">Prod
  <button type="button" onclick="this.parentNode.style.visibility='hidden'" class="prodButton">Hide</button>
</div>
<div id="test">Test
  <button type="button" onclick="this.parentNode.style.visibility='hidden'" class="testButton">Hide</button>
</div>
<div id="dev">Dev
  <button type="button" onclick="this.parentNode.style.visibility='hidden'" class="devButton">Hide</button>
</div>

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