What is the Difference between onclick and href="javascript:function name?
Is there any difference between
1 : <a href=开发者_JS百科"javascript:MyFunction()">Link1</a>
and
2 : <a href="#" onclick="MyFunction()">Link2</a>
? Would one affect the page performance by any means ?
If your element is not actually supposed to link the user someplace, don't make it an anchor element. If you're using <a>
tags just to get the underline/cursor change - don't. Use CSS on a <span>
(or other element) instead.
span.link {
text-decoration: underline;
color: blue;
cursor: pointer;
}
Keep your HTML semantic and use anchor elements only when you want to link the user somewhere.
No performance difference.
The first is crap because it will fail completely for users without JS enabled.
The second is still crap, but would be better if the href
pointed to a URL for users without JS enabled.
The onclick version allows you pass 'this' as an argument, so you can refer back to the tag/object the click came from. Not possible with the protocol method:
<a href="#" onclick="alert(this.innerHTML)">yo yo yo</a>
will spit out an alert popup with "yo yo yo", whereas
<a href="javascript:alert(this.innerHTML)">yo yo yo</a>
will spit out 'undefined'.
An href="javascript: doSomething" means you do not have a url to fallback to if the user doesn't have js enabled.
Therefore, setting href="something.html" and onclick="return doSomething()" is usually considered better because if js is disabled, you can navigate to a new page, but if js is enabled, you can return false to prevent navigation to the link and display something within the same page without a page refresh.
Even better, don't add the onclick inline, just add js handlers when the page loads. That's the unobtrusive way
There is a difference in functionality, the first doesn't attempt to process a link. The second does.
However, I agree with Coronatus - both methods are not ideal. I would suggest researching unobtrusive JavaScript (perhaps with jQuery) as you could dynamically add a click event to the element.
If your website requires Javascript in order to function correctly then Javascript in the href is best because it shows the link in the status bar and keeps the code compact. In the href also serves keyboard navigation without the mouse. If your website is required to function without Javascript then you have to use onclick so the href can have a link in it. Adding the action in a separate Javascript file fails to keep code & data bound tightly.
精彩评论