Home > Web Front-end > JS Tutorial > Why Is the onclick Handler Triggered on Page Load Instead of When Clicking the Link?

Why Is the onclick Handler Triggered on Page Load Instead of When Clicking the Link?

Patricia Arquette
Release: 2024-10-22 07:18:31
Original
357 people have browsed it

Why Is the onclick Handler Triggered on Page Load Instead of When Clicking the Link?

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

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

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!

source:php
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