button onclick wont call the javascript function

时间:2016-09-21 05:47:43

标签: javascript

I am calling a function on a button click. But the function is not getting called. I dont know what I am doing wrong. Please help.

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clear() {
      document.getElementById('inp').value = "";
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clear()">
</body>
</html>

3 个答案:

答案 0 :(得分:5)

clear不是保留字,而是调用document.clear。尝试更新功能名称

示例

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clear1() {
      document.getElementById('inp').value = "";
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clear1()">
</body>
</html>

示例 - 覆盖document.clear

注意:覆盖document/window/prototype函数是一种不好的做法。这仅用于演示目的。

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clear1() {
      document.getElementById('inp').value = "";
    }
    document.clear = function(){
      console.log('My clear function')
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clear()">
</body>
</html>

参考

Is “clear” a reserved word in Javascript?

答案 1 :(得分:0)

更改功能名称,因为清除功能会导致该问题。使函数名称为clearInput或方便的

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script type="text/javascript">
    function clearTxtBox() {
      document.getElementById('inp').value = "";
    }
  </script>
</head>

<body>
  <input type="text" id="inp" name="">
  <input type="button" onclick="clearTxtBox()">
</body>
</html>

只需更改您的功能名称即可。