DIV'内联阻止'或没有使用复选框不工作

时间:2013-05-26 17:32:07

标签: javascript css html

我已经阅读了几个例子,但仍然无法让它正常工作。我只是想通过单击复选框使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>

谢谢!

1 个答案:

答案 0 :(得分:2)

你用两次“getElementyById”错误拼写了“getElementById”。

此外,在if语句中,请务必使用“==”进行比较,而不是“=”。

<强>错误:

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

从右:

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

应该在这些变化之后工作。