简体   繁体   中英

Having trouble with conditional html “programming”

Old onetime mainframe programmer. Trying to conditionally display or not display html. Searched and tried numerous suggestions. No luck. Would greatly appreciate help. Latest test attempt:

<html>
<head>
<title>July 27 - Lang Bay </title>
</head>
<script language="javascript">
    var x = 0;
    function hola(x) {
        if(x == 0) {           
          document.getElementById("showpage").style.visibility="hidden";
        }
    }
</script>
<body>
<div id="showpage">
    <p><font size=+1>July 27 - Lang Bay </font>
    <br><TABLE>
    <TR>
    <TD><br><a href="../../jpg/2009/090727_052p.jpg"><img SRC="../../jpg/2009/090727_052ptn.jpg"><br>B.C., Lang Bay<br>Afternoon on the beach </a>
    <TD><br><a href="../../jpg/2009/090727_053p.jpg"><img SRC="../../jpg/2009/090727_053ptn.jpg"><br>B.C., Lang Bay<br>Heather McCutcheon, Sydney </a>
</div>

</body> 
</html>

The language attribute for script elements was deprecated in HTML 4 (1999) and has been removed in later versions. Don't use it.

In your code there is:

var x = 0;
function hola(x) {
  if (x == 0) {           
    document.getElementById("showpage").style.visibility="hidden";
  }
}

When you provide a parameter in the formal parameter list of a function declaration (ie the x in function hola(x){...} then it's equivalent to declaring the variable inside the function body, so x in the function references that local x , not the global one. You can either remove x from the parameter list, or pass it in the call, eg

function hola() {
  // use global x
}

or

function hola(x) {
  // use local x
}

// pass value of global x in the call
hola(x);

Since you haven't shown how hola is called, the simplest fix is the second.

As the comments have said, you need to call the function after the elements have loaded. Use window.onload for that:

window.onload = function() {
  hola(x);
}

Simple answer: wait for the window to load, then call hola . (In javascript, you need to call functions to invoke the code inside them).

window.addEventListener('load', function() {
  hola(0);
});

Additionally, you need to pass 0 into hola , because the x parameter declared in hola overrides the global variable x .

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