实时代码:http://jsfiddle.net/vy4nY/

我正在关注this challenge,但遇到了一些问题。我试图使“电子邮件地址”框仅在单击复选框时出现。我做错了什么?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <title>JavaScript Challenges</title>
    <style type="text/css">
    #emailpara {visibility:hidden;}
    </style>
  </head>
  <body>
    <form action="">
      <fieldset>

        <legend>Email subscriptions</legend>

        <p id="subscribepara">
          <label>
            <input type="checkbox" name="subscribe" id="subscribe">
            Yes! I would like to receive the occasional newsletter via email.
          </label>
        </p>

        <p id="emailpara">
          <label>
            Email Address:
            <input type="text" name="email" id="email">
          </label>
        </p>

      </fieldset>
    </form>
      <script type="text/javascript">
document.getElementById('subscribe').onclick = (document.getElementById('subscribe').checked ? (document.getElementById('emailpara').style.visibility = 'visible') : (document.getElementById('emailpara').style.visibility = 'hidden'));
      </script>
  </body>
</html>

最佳答案

onclick处理程序应该是一个函数。用:

document.getElementById('subscribe').onclick = function() {
    document.getElementById('emailpara').style.visibility = this.checked ? 'visible' : 'hidden';
}

07-28 07:20