带有 Javascript onclick 事件的 HTML 锚标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7347786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:55:06  来源:igfitidea点击:

HTML anchor tag with Javascript onclick event

javascripthyperlinkonclickanchor

提问by smartkid

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

在使用 Google 时,我发现他们在锚标签中使用 onclick 事件。

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

在google header 部分的更多选项中,它看起来像一个普通的标签,但点击它不会被重定向,而是打开了一个菜单。通常在使用时

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

它通常会在不触发的情况下转到“more.php” show_more_menu(),但我在该页面中显示了一个菜单。如何像谷歌一样?

回答by TJHeuvel

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

如果您的 onclick 函数返回 false,则默认浏览器行为将被取消。像这样:

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

不管怎样,谷歌是否这样做并不重要。将您的 onclick 函数绑定到 javascript 中会更简洁 - 这样您就可以将 HTML 与其他代码分开。

回答by sun2

You can even try below option:

您甚至可以尝试以下选项:

<a href="javascript:show_more_menu();">More >>></a>

回答by Aditya Manohar

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>

回答by Kamil Kie?czewski

Use following code to show menu instead go to href addres

使用以下代码显示菜单,而不是转到 href 地址

function show_more_menu(e) {
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();
}
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>