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.
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