Home > Web Front-end > JS Tutorial > body text

Why Does JavaScript onclick Function Trigger Prematurely When Parentheses Are Used?

Patricia Arquette
Release: 2024-10-22 07:10:03
Original
648 people have browsed it

Why Does JavaScript onclick Function Trigger Prematurely When Parentheses Are Used?

JavaScript onclick Function Triggered Prematurely

When creating a link with similar aesthetics to an tag but intended to execute a function upon click, users may encounter a scenario where the function is erroneously called upon page load. This precludes the desired click event from functioning correctly.

The common pitfall is the improper use of parentheses when assigning the onclick attribute. Instead of sentNode.onclick = secondFunction(), which immediately executes the function, the correct syntax is sentNode.onclick = secondFunction. This assigns a reference to the function, which will only be executed upon the click event.

<code class="javascript">function startFunction() {
  var sentNode = document.createElement('a');
  sentNode.setAttribute('href', "#");
  sentNode.setAttribute('onclick', secondFunction);
  //sentNode.onclick = secondFunction();
  sentNode.innerHTML = "Sent Items";
  //...
}</code>
Copy after login

By omitting the parentheses, the onclick event is correctly bound to a function reference and not the result of its execution, ensuring the intended behavior.

The above is the detailed content of Why Does JavaScript onclick Function Trigger Prematurely When Parentheses Are Used?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!