Mejores prácticas para JS - en href o en onclick?

Just a question about optimization, between :

<a href="#" onClick="'');">link-1</a>


<a href="'');">link-2</a>

Is one better than the other ? Or more compatible ? Thanks.

preguntado el 12 de junio de 12 a las 17:06

Neither is preferred. You should look into JavaScript event binding, and listen for the click on the link. -

4 Respuestas

La mejor práctica es utilizar el target atributo:

<a href="" target="_blank">link-1</a>

If that doesn't suit, a click handler (ideally not assigned via attribute) would be my take.

Respondido el 12 de junio de 12 a las 17:06

Why is this the better practise? - Dwjohnston

@dwjohnston - It's semantic, so the browser (/screen reader, etc.) can indicate what's going to happen, and no JavaScript is required. - TJ Crowder

Ninguno de los dos

Make it a regular link using href y target

<a id='my-link' target="_blank" href="">link-2</a>

If you need to do some processing of the click with JavaScript, you can use the following

document.getElementById("my-link").onclick = function(e) {
  // Do some processing here, maybe 
  window.location = this.href
  // Return false to prevent the default action if you did redirect with script
  return false;

Respondido el 12 de junio de 12 a las 17:06

Sin JavaScript

<a target="_blank" href="">link</a>

Con JavaScript

<a target="_blank" href="" id="myLink">link</a>
    document.getElementById("myLink").onclick = function(){ //attach click event to link
        var winPop =;  //`this` is reference to link, get href
        return false;  //prevent click event from clicking the link

Ejemplo de JSFiddle

Respondido el 12 de junio de 12 a las 17:06

Below code should be fine.

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

Found issue in IE (version:11) with below code

<a onclick="">

Problem: The parent window is getting refreshed in IE when we have javascript code in href attribute.

Respondido el 08 de diciembre de 15 a las 11:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.