When attempting to trigger JavaScript functions on hyperlink clicks without causing page redirections, a question arises regarding the appropriate usage of the href and onclick attributes.
Putting the JavaScript call in the href attribute may result in the browser executing both the JavaScript code and the link redirection. This behavior is discouraged as it can lead to unexpected results.
Incorrect usage:
<a href="javascript:my_function();window.print();">...</a>
Binding the JavaScript call to the onclick event provides more control over the behavior. It allows for the execution of the JavaScript code while preventing the redirection.
Recommended usage:
<a href="#" onclick="MyFunction(); return false;">...</a>
The "return false;" statement ensures that the browser does not follow the link.
The best approach involves utilizing a framework like jQuery to attach the onclick event handler by the element's ID. This provides greater flexibility and avoids potential issues with href usage.
Optimal solution:
$('#myLink').click(function() { MyFunction(); return false; });
The above is the detailed content of JavaScript Hyperlinks: href vs onclick - Which is Best for Function Calls?. For more information, please follow other related articles on the PHP Chinese website!