简体   繁体   中英

How to use href and onclick on <a> tag simultaneously?

I want to use href as well as onclick one after another. I am trying like this, but my javascript function is not called? Is it the right approach to do so?

<a href="register.php" title="" onclick="javaScript:showRegisterRules();">Register</a>

function showRegisterRules()
{
 alert("Registration Rules");
}

How can I achieve my functionality?

Something like:

<a href="javascript:void()" title="" onclick="javaScript:showRegisterRules('register.php');">Register</a>

function showRegisterRules(url)
{
 alert("Registration Rules");

 //Go to your url
 document.location.href=url;
}

JS

<script type="text/javascript">
    function showRegisterRules()
    {
     alert("Registration Rules");
    }

</script>

HTML

 <a href="register.php" title="" onclick="showRegisterRules();">Register</a>

Just one Question

Did you put the javascript in script tag ? Because once I did this it worked

<a href="register.php" title="" onclick="javaScript:showRegisterRules();">Register</a>

JS

<script>
    function showRegisterRules()
    {
     alert("Registration Rules");
    }

</script>

尝试这个:

<a href="#" title="" onclick="javaScript:showRegisterRules();window.location.href='register.php'">Register</a>

You can actually write a generic method here rather than one spessific to any given URL.

<a href="register.php" title="" onclick="showRegisterRules(this);">Register</a>

function showRegisterRules(a)
{
    alert("Registration Rules");
    document.location.href=a.href;
}

This way, you can reuse the same method anywhere within the site to show the alert. This allowing it to go in a script file rather than the html page

You can do this also

<a href="register.php" title="" onclick="return showRegisterRules('register.php');">Register</a>

function showRegisterRules(url)
{
 alert("Registration Rules");

 return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM