"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does JavaScript onclick Function Trigger Prematurely When Parentheses Are Used?

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

Published on 2024-11-10
Browse:481

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.

function startFunction() {
  var sentNode = document.createElement('a');
  sentNode.setAttribute('href', "#");
  sentNode.setAttribute('onclick', secondFunction);
  //sentNode.onclick = secondFunction();
  sentNode.innerHTML = "Sent Items";
  //...
}

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.

Release Statement This article is reprinted at: 1729552154 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3