Which is the best way to call a javascript function on a link

匆匆过客 提交于 2019-12-12 12:21:37

问题


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?


回答1:


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




回答2:


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




回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/3681787/which-is-the-best-way-to-call-a-javascript-function-on-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!