Home >Web Front-end >JS Tutorial >JavaScript Hyperlinks: href vs onclick - Which is Best for Function Calls?

JavaScript Hyperlinks: href vs onclick - Which is Best for Function Calls?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 21:01:02526browse

JavaScript Hyperlinks: href vs onclick - Which is Best for Function Calls?

JavaScript - Callback Functions for Hyperlinks: href vs onclick

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.

href Attribute

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>

onclick Attribute

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.

Best Practice

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!

Statement:
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