HTML anchor tag with Javascript onclick event

2019-01-17 02:05发布

On using Google I found that they are using onclick events in anchor tags.

In more option in google header part, it looks like normal a tag, but onclicking it doesn't get redirected but opened a menu. Normally when using

<a href='more.php' onclick='show_more_menu()'>More >>></a>

It usually goes to 'more.php' without firing show_more_menu(), but I have show a menu in that page itself. How to do like google?

4条回答
三岁会撩人
2楼-- · 2019-01-17 02:54

If your onclick function returns false the default browser behaviour is cancelled. As such:

<a href='http://www.google.com' onclick='return check()'>check</a>

<script type='text/javascript'>

function check()
{
    return false;
}

</script>

Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

查看更多
叛逆
3楼-- · 2019-01-17 02:55

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-17 02:57

You can even try below option:

<a href="javascript:show_more_menu();">More >>></a>
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-17 02:58

Use following code to show menu instead go to href addres

<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>

<script>
    function show_more_menu(e) {
        // ...  your function code
        // e.target.href  // a.href url
        e.preventDefault();
    }
</script>

Here is working example.

查看更多
登录 后发表回答