HTML tag want to add both href and onclick wor

2019-01-03 23:54发布

I'd like to ask about HTML tag

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

How to make this a tag working with href and onClick? (prefer onClick running first then href)

4条回答
可以哭但决不认输i
2楼-- · 2019-01-04 00:05

You already have what you need, with a minor syntax change:

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

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)

查看更多
淡お忘
3楼-- · 2019-01-04 00:06

To achieve this use following 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>

Here is working example.

查看更多
Animai°情兽
4楼-- · 2019-01-04 00:07

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="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>
查看更多
劫难
5楼-- · 2019-01-04 00:13

Use jQuery. You need to capture the click event and then go on to the website.

$("#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>

查看更多
登录 后发表回答