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!