简体   繁体   English

如何从href调用javascript?

[英]How to call javascript from a href?

How to call javascript from a href? 如何从href调用javascript?

like: 喜欢:

<a href="<script type='text/javascript'>script code</script>/">Call JavaScript</a>

<a onClick="yourFunction(); return false;" href="fallback.html">One Way</a>

** Edit ** ** 编辑 **
From the flurry of comments, I'm sharing the resources given/found. 从一连串的评论中,我将分享给定/找到的资源。

Previous SO Q and A's: 以前的SO Q和A:

Interesting reads: 有趣的读物:

<a href="javascript:call_func();">...</a>

where the function then has to return false so that the browser doesn't go to another page. 然后函数必须返回false,以便浏览器不会转到另一个页面。

But I'd recommend to use jQuery (with $(...).click(function () {})) ) 但我建议使用jQuery(带$(...).click(function () {}))

The proper way to invoke javascript code when clicking a link would be to add an onclick handler: 单击链接时调用javascript代码的正确方法是添加onclick处理程序:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded. 虽然一个更“合适”的方法是将它全部从html中取出并在加载dom时用另一个javascript添加处理程序。

Using JQuery would be good; 使用JQuery会很好;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});

JavaScript code is usually called from the onclick event of a link. JavaScript代码通常是从链接的onclick事件中调用的。 For example, you could instead do: 例如,您可以改为:

In Head Section of HTML Document 在HTML文档的头部分

<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>

In Body of HTML Document 在HTML文档正文中

<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>

Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery. 或者,您也可以使用链接的ID,HTML DOM或JQuery等框架将您的函数附加到链接。

For example: 例如:

In Head Section of HTML Document 在HTML文档的头部分

<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>

In Body of HTML Document 在HTML文档正文中

<a href="#" id="mylink">Call JavaScript </a>

I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" /> for this. 我会完全避免使用内联javascript,正如我在评论中提到的,我也可能会使用<input type="button" /> That being said... 话虽如此...

<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>

var clickHandler = function() {
     alert('Stuff happens now.');   
}


if (document.addEventListener) {
    document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
    document.getElementById('mylink').attachEvent('click', clickHandler);
}

http://jsfiddle.net/pDp4T/1/ http://jsfiddle.net/pDp4T/1/

Not sure why this worked for me while nothing else did but just in case anyone else is still looking... 不知道为什么这对我有用,而没有其他事情,但以防万一其他人仍在寻找......

In between head tags: 在头部标签之间:

<script>
     function myFunction() {
           script code
     }
</script>

Then for the < a > tag: 然后是<a>标签:

<a href='' onclick='myFunction()' > Call Function </a>

如果您只想处理函数而不是自己处理href,请在函数末尾添加return false语句:

 <a href="#" onclick="javascript: function() {... ; return false} return false">click</>

另一种方式是:

<a href="javascript:void(0);" onclick="alert('testing')">

编辑这将在单击编辑函数名称后创建一个带编辑的链接,因为将调用编辑

 <a href="javascript:
  console.dir(Object.getOwnPropertyDescriptors(HTMLDivElement))">
       1. Direct Action Without Following href Link
  </a>

<br><br>

  <a href="javascript:my_func('http://diasmath.blogg.org')">
      2. Indirect Action (Function Call) Without Following Normal href Link
  </a>

<br><br>

 <!-- Avec « return false » l'action par défaut de l'élément
 // <a></a> (ouverture de l'URL pointée par
 // « href="http://www.centerblog.net/gha" »)
 // ne s'exécute pas.
 -->
 <a target=_new href="http://www.centerblog.net/gha"
          onclick="my_func('http://diasmath.blogg.org');
 return false">
     3. Suivi par défaut du Lien Normal href Désactivé avec
     « return false »
  </a>

<br><br>

 <!-- Avec ou sans « return true » l'action par défaut de l'élément
 // s'exécute pas.
 -->
 <a target=_new href="http://gha.centerblog.net"
          onclick="my_func('http://diasmath.blogg.org');">
     4. Suivi par défaut du Lien Normal href Conservé avec ou sans
     « return true » qui est la valeur retournée par défaut.
  </a>

<br><br>

<!-- Le diese tout seul ne suit pas le lien href. -->
  <a href="#" onclick="my_func('http://diasmath.blogg.org')">
      5. Lien Dièse en Singleton (pas de suivi href)
  </a>

  <script language="JavaScript">
   function my_func(s) {
       console.dir(Object.getOwnPropertyDescriptors(Document));
       window.open(s)
   }
  </script>

<br>
<br>

 <!-- Avec GESTION D'ÉVÉNEMENT.
 // Événement (event) = click du lien
 // Event Listener = "click"
 // my_func2 = gestionnaire d'événement
 -->
  <script language="JavaScript">
   function my_func2(event) {
      console.dir(event);
      window.open(event.originalTarget["href"])
   }
  </script>
 <a target=_blank href="http://dmedit.centerblog.net"
     id="newel" onclick="return false">
     6. By specifying another eventlistener
     (and deactivating the default).
  </a>
  <script language="JavaScript">
      let a=document.getElementById("newel");
      a.addEventListener("click",my_func2)
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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