Javascript: Unexpected Invocation of onclick Handler
When attempting to create a link that resembles an anchor tag but executes a custom function, the onclick function is invoked immediately upon page load, rendering subsequent clicks ineffective.
Explanation:
In the provided code snippet:
<code class="javascript">var sendNode = document.createElement('a'); sendNode.setAttribute('onclick', secondFunction());</code>
The line setAttribute('onclick', secondFunction()) is incorrect. It immediately executes the secondFunction function and assigns its return value (typically undefined) to the onclick attribute. This leads to the immediate invocation of the secondFunction.
Solution:
To correctly assign the secondFunction as an event handler, the correct syntax is:
<code class="javascript">var sendNode = document.createElement('a'); sendNode.setAttribute('onclick', secondFunction);</code>
This creates an event listener that waits for a click event on the element before invoking the secondFunction.
The above is the detailed content of Why Is the onclick Handler Triggered on Page Load Instead of When Clicking the Link?. For more information, please follow other related articles on the PHP Chinese website!