Etiqueta HTML desea agregar href y onclick trabajando


Me gustaría preguntar sobre la etiqueta HTML

<a href="www.mysite.com" onClick="javascript.function();">Item</a>

Cómo hacer que este un etiqueta de trabajo con href y onClick? (prefiera que onClick se ejecute primero y luego href)

Author: Ian, 2013-02-14

3 answers

Ya tienes lo que necesitas, con un pequeño cambio de sintaxis:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

El comportamiento predeterminado de las propiedades <a> de la etiqueta onclick y href es ejecutar el onclick, luego seguir el href siempre y cuando el onclick no devuelva false, cancelando el evento (o el evento no se ha evitado)

 184
Author: Ian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-14 04:01:44

Use jQuery. Necesitas capturar el evento click y luego ir al sitio web.

$("#myHref").on('click', function() {
  alert("inside onclick");
  window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myHref">Click me</a>
 8
Author: Sudipta Chatterjee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 15:29:46

Para lograr esto use el siguiente html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Aquí está ejemplo de trabajo.

 0
Author: Kamil Kiełczewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-02 07:33:38