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

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

Linda Hamilton
Release: 2024-12-24 21:12:12
Original
1004 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template