0

我已经阅读了几个示例,但仍然无法使其正常工作。我只是想通过单击复选框使 DIV 可见和不可见。我是否正确编码了javascript?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SimpleSample - Hidden Div</title>
</head>

<script type="text/Javascript">
function showhideDiv1() {
   if (document.getElementyById('div1').style.display = "none") {
      //show the div:
      document.getElementById('div1').style.display = "block";
   }
   else {
      //hide the div:
      document.getElementById('div1').style.display = "none";
      //clear the form:
      //document.getElementById('myform').reset();
   }
}

function showhideDiv2() {
   if (document.getElementyById('div2').style.display = "none") {
      //show the div:
      document.getElementById('div2').style.display = "block";
   }
   else {
      //hide the div:
      document.getElementById('div2').style.display = "none";
      //clear the form:
      //document.getElementById('myform').reset();
   }
}
</script>

<body>
<form id="myform" name="myform" method="post" action="">
  <div id="div1">
    <p>Content for  id "div1" Goes Here</p>
    <table width="800" border="0">
      <tr>
        <td>First Name</td>
        <td><input name="fname" type="text" id="fname" value="" /></td>
      </tr>
      <tr>
        <td>Last Name</td>
        <td><input name="lname" type="text" id="lname" value="" /></td>
      </tr>
    </table>
   </div>

    <div id="div2">
      <p>Content for  id "div2" Goes Here</p>
      <table width="800" border="0">
        <tr>
          <td width="258">Email</td>
          <td width="532"><input name="emailAddr" type="text" id="emailAddr" value="" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
      </table>
    </div>

    <div id="div3">
      <p>Content for  id "floatingDiv" (when ready) Goes Here</p>
      <table width="800" border="0">
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td><input onchange="showhideDiv1();" name="showDiv1Chk" type="checkbox" id="showDiv1Chk" checked="checked" />
            - Show Div1</td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td><input onchange="showhideDiv2();" name="showDiv2Chk" type="checkbox" id="showDiv2Chk" checked="checked" />
            - Show Div2</td>
          <td> &nbsp;</td>
        </tr>
      </table>
    </div>
    <p>&nbsp;</p>

</form>
</body>
</html>

谢谢!

4

1 回答 1

2

您将“getElementById”与“getElementyById”拼错了两次。

此外,在您的 if 语句中,请确保使用“==”而不是“=”进行比较。

错误的:

if (document.getElementById('div1').style.display = "none")

正确的:

if (document.getElementById('div1').style.display == "none")

应该在这些更改之后工作。

于 2013-05-26T17:37:04.097 回答