简体   繁体   中英

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 best 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?

由于这不是一个真正的链接(功能上或视觉上),你应该坚持使用<span> (如果你想要一个块级元素,那么<div> )。

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM