Which is the best way to call a javascript function on a link
I want to add some links to some website of mine, but these links will call a javascript function and will not be underlined, also I want the cursor to be changed to a standard pointer. Which is the be开发者_开发知识库st way of doing it and why?
Right now I can think of two aproaches:
<a href="javascript:someFunction()" style="text-decoration:none">LINK</a>
or
<span onClick="someFunction();" style="cursor: pointer;">LINK</span>
Which one do you think is better?
Since this isn't really going to be a link (functionally or visually) you should stick with a <span>
(or <div>
if you want a block level element).
"The HTML <span>
tag is used for grouping and applying styles to inline elements. When the text is hooked in a span element you can add styles to the content, or manipulate the content with for example JavaScript." -W3
"The <a>
tag defines a hyperlink, which is used to link from one page to another." -W3
If you're only calling a function I would use span.
I like v2, just because I would rather not have javascript functions in the url bar. What happens when they click the v1 link, and then bookmark?
I think a combination is better:
<a href="#" id="myLink">LINK</a>
$(document).ready({
$('#myLink').click(function() { someFunction(); return false; });
});
If possible try putting a real URL in the href
. By including a real href in the link you're allowing people to either experience the javascript version of your link (such as an ajax refresh) or right click and go to the real destination.
Of course this isn't always practical, your site might require that the action only be completed through a popup dialog. Ideally though the user should be open a link in another window/tab by following the href.
精彩评论