如何使用链接来调用JavaScript?

如何使用链接调用JavaScript代码?

<a onclick="jsfunction()" href="#"> 

要么

 <a onclick="jsfunction()" href="javascript:void(0);"> 

编辑:

上面的回答真的不是一个好的解决scheme,从我最初发布了解了很多关于JS。 请参阅下面的EndangeredMassa的答案以解决这个问题。

不显眼的JavaScript,没有库依赖:

 <html> <head> <script type="text/javascript"> // Wait for the page to load first window.onload = function() { //Get a reference to the link on the page // with an id of "mylink" var a = document.getElementById("mylink"); //Set code to run when the link is clicked // by assigning a function to "onclick" a.onclick = function() { // Your code here... //If you don't want the link to actually // redirect the browser to another page, // "google.com" in our example here, then // return false at the end of this block. // Note that this also prevents event bubbling, // which is probably what we want here, but won't // always be the case. return false; } } </script> </head> <body> <a id="mylink" href="http://www.google.com">linky</a> </body> </html> 

而且,为什么不使用jQuery不显眼:

  $(function() { $("#unobtrusive").click(function(e) { e.preventDefault(); // if desired... // other methods to call... }); }); 

HTML

 <a id="unobtrusive" href="http://jquery.com">jquery</a> 
 <a href="javascript:alert('Hello!');">Clicky</a> 

编辑,多年后:不! 永远不要这样做! 我当时年less无知!

或者,如果你正在使用PrototypeJS

 <script type="text/javascript> Event.observe( $('thelink'), 'click', function(event) { //do stuff Event.stop(event); } </script> <a href="#" id="thelink">This is the link</a> 

不引人注目的Javascript有许多优点,这是它需要的步骤,以及为什么它是好的使用。

  1. 链接加载正常:

    <a id="DaLink" href="http://host/toAnewPage.html">点击此处</a>;

这很重要,因为它将适用于未启用JavaScript的浏览器,或者如果在JavaScript代码中有错误,则不起作用。

  1. JavaScript运行在页面加载:

      window.onload = function(){ document.getElementById("DaLink").onclick = function(){ if(funcitonToCall()){ // most important step in this whole process return false; } } } 
  2. 如果JavaScript运行成功,也许用javascript加载当前页面中的内容,返回false将取消链接触发。 换句话说,如果JavaScript成功运行,则返回false将导致禁用链接。 虽然允许它运行,如果没有JavaScript,做一个很好的备份,以便您的内容显示任何方式,search引擎,如果您的代码中断,或在非JavaScript系统上查看。

关于这个问题的最好的书是杰里米·基思(Jeremy Keith)的“Dom Scription”

我认为你可以使用onclick事件,就像这样:

 <a onclick="jsFunction();"> 
 <a href="javascript:void(code)"></a>