【问题标题】:TypeError: - is not a functionTypeError: - 不是函数
【发布时间】:2020-06-29 02:11:50
【问题描述】:

我有这个 form 应该隐藏另一个表单:

  <!--checkbox-->
  <form method="POST" action="start.inc.php">
      <span id="switch"><!--these are for css, the input matters-->
          <label>
              <input id="hide" name="hide" type="checkbox" onclick="hide()" /><!--error here-->
              <span class="slider"></span>
          </label>
          <label for="hide">Do not set a password</label>
      </span>
  </form>

  <!--this should be hidden-->
  <form method="POST" action="start.inc.php">
      <!--form stuff-->
    <button type="submit" name="check">Set Password</button>
  </form>

所以我实现了这样一个函数:

function hide() {
    var checkBox = document.getElementById("hide");
    var form =  document.getElementsByTagName("form")[1];

    if (checkBox.checked == true)
    {
        form.style.display = "none";
    } else {
        form.style.display = "block";
    }
}

它写在之前 html,但即使改变它们的顺序也没有任何改变......

问题是,当我单击复选框时,表单并没有消失,并且我在控制台上收到以下错误: (index):93 Uncaught TypeError: hide is not a function at HTMLInputElement.onclick

注意:我是 JS 的初学者,所以如果这是一个愚蠢的错误请不要喷我

谢谢

【问题讨论】:

    标签: javascript html function console


    【解决方案1】:

    问题是函数的名字和元素的ID一样。元素 ID 成为全局变量,因此 hide&lt;input&gt; 元素而不是函数。实现这一点的关键是错误消息并没有说hide 是未定义的,而是说它不是一个函数——这意味着它是其他东西(在这种情况下,是一个 DOM 元素)。

    给函数起一个与任何元素 ID 不同的名称,它会起作用。

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2021-06-05
    • 2019-10-03
    • 2017-03-06
    • 2018-12-23
    • 2021-08-12
    相关资源
    最近更新 更多