Home >Web Front-end >JS Tutorial >Why Doesn't `onclick='clear()'` Work in JavaScript?

Why Doesn't `onclick='clear()'` Work in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 21:12:121008browse

Why Doesn't `onclick=

onclick="clear()" Not Functioning: Understanding the JavaScript Obstacle

In an attempt to create a basic calculator, one encounters a puzzling issue: the "clear" button, assigned with the onclick="clear()" attribute, fails to execute its intended function of clearing the text field.

The enigma lies within JavaScript's intrinsic event attributes, such as onclick. These attributes use the with statement, a discouraged practice due to its potential for confusion and compatibility concerns. Consequently, the onclick="clear()" attribute inadvertently invokes document.clear() rather than the intended global function clear().

To resolve this issue, one can rename the clear function or explicitly call window.clear(). However, a superior solution is to employ addEventListener for event binding, which circumvents the use of intrinsic event attributes.

The following code sample demonstrates the proper implementation using addEventListener:

<script>
  const clearButton = document.querySelector('input[value="C"]');
  clearButton.addEventListener('click', clear);

  function clear() {
    document.getElementById("field").value = "";
  }
</script>

The above is the detailed content of Why Doesn't `onclick='clear()'` Work in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn