Home >Web Front-end >JS Tutorial >Why Doesn't `onclick='clear()'` Work and How Can I Fix It?
Why onclick="clear()" Doesn't Work
When attempting to execute a function named "clear()" using the onclick attribute, the function may fail to execute. This is due to intrinsic event attributes, such as onclick, employing the with statement.
The Issue: with Statement
The with statement is strongly discouraged as it can lead to confusing bugs and compatibility issues. When onclick="clear()" is used, it erroneously calls document.clear() instead of the desired global function clear().
Quick Fix
To resolve the issue, rename the clear() function to avoid using the reserved word "clear" or explicitly call window.clear().
Recommended Solution: addEventListener
A more robust solution is to utilize addEventListener to bind event handlers. This method is preferred over intrinsic event attributes as it provides a clear and reliable way to associate events with functions.
Example:
<button onclick="clear()">C</button>
Can be rewritten using addEventListener:
<button>
By leveraging addEventListener, the event handler is properly bound to the global clear() function, ensuring its successful execution when the button is clicked.
The above is the detailed content of Why Doesn't `onclick='clear()'` Work and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!