Click me...">

How to execute onClick and href like in Anchot tag (<a>)

I have a link as follows:

<a href="www.google.com" onClick="someFunction()">Click me</a>

When a link is clicked, the JavaScript function is executed, but not bound to the href link.

Any ideas on how to achieve the same?

+3
source share
4 answers

I think the easiest way to do this is to return the function true, so that after the function completes, the anchor tag will behave as usual. Thus, you can also use the target attribute if you want to use a new window:

<a href='http://www.google.com' onclick="myFunction();" target="google">Click me</a>

Script

<script type='text/javascript'>
    function myFunction() {
        alert("hello");
        return true;
    }
</script>
+7
source

I used jQuery, I hope it is still clear:

<a href="www.google.com" onClick=someFunction()>Click me </a>

Executes the js function, but does not lead me to the href link.

So, ONE way to add redirection after your function:

function someFunction()
{
  ... your code ...

  window.location.href(   $(this).attr('href')  );   // <-----  HERE

}

:

  function someFunction()
    {
      ... your code ...

     window.open(    $(this).attr('href') , '_blank'  );   // <-----  HERE

    }
+3

,

<div onclick = "function();"><a href = "link.com">link here</a> </div>

onclick

<a href = "link.com" onclick = "function();"> link here</a>

onclick , , , .

: , true, , href .

+1

, .

.click 'a', " " javascript.

, "click" javascript. "a" onClick, ( , ).

, , "click" 'a', href onClick, .

onclick, href.

:

$('a').click(function () {
                window.open($(this).attr('href'));                
});

http://jsfiddle.net/4Qku8/, jquery.

.

-2

All Articles