write usuario tipos tecla qué oprima mover llamar hace función funciones forma externo ejecutar desde cuando cualquier archivo javascript

usuario - tipos de funciones en javascript



¿Cómo usar un enlace para llamar a JavaScript? (7)

Creo que puedes usar el evento onclick , algo como esto:

<a onclick="jsFunction();">

¿Cómo usar un enlace para llamar al código JavaScript?


JavaScript discreto, sin dependencia de la biblioteca:

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


Javascript discreto tiene muchas ventajas, estos son los pasos que debe seguir y por qué es bueno usarlos.

  1. el enlace se carga de forma normal:

    <a id="DaLink" href="http://host/toAnewPage.html"> haga clic aquí </a>

esto es importante porque funcionará para navegadores con javascript no habilitado, o si hay un error en el código de javascript que no funciona.

  1. javascript se ejecuta en la carga de la página:

    window.onload = function(){ document.getElementById("DaLink").onclick = function(){ if(funcitonToCall()){ // most important step in this whole process return false; } } }

  2. si el javascript se ejecuta con éxito, tal vez cargando el contenido en la página actual con javascript, el retorno falso cancela la activación del enlace. en otras palabras, poner return false tiene el efecto de deshabilitar el enlace si el javascript se ejecutó correctamente. Si bien permite que se ejecute si el javascript no lo hace, haciendo una buena copia de seguridad para que su contenido se muestre de cualquier manera, para los motores de búsqueda y si su código se rompe, o se ve en un sistema que no es javascript.

El mejor libro sobre el tema es "Dom Scription" por Jeremy Keith


O bien, si está utilizando 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>


Y, ¿por qué no discreto con 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>

EDITAR, años después: ¡NO! ¡Nunca hagas esto! ¡Era joven y estúpido!


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

o

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

Editar:

La respuesta anterior no es realmente una buena solución, ya que aprendí mucho sobre JS desde que publiqué inicialmente. Consulte la respuesta de EndangeredMassa a continuación para obtener un mejor enfoque para resolver este problema.