Mejores prácticas para JS - window.open() en href o en onclick?

Just a question about optimization, between :

<a href="#" onClick="javascript:window.open('myUrl.com');">link-1</a>

y:

<a href="javascript:window.open('myUrlBis.com');">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="http://myUrl.com" 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="http://myUrlBis.com">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="myUrlBis.com">link</a>

Con JavaScript

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

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="window.open(url)">

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

<a onclick="javascript:window.open(url)">

Problem: The parent window is getting refreshed in IE when we have javascript window.open 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.