带有 Javascript onclick 事件的 HTML 锚标记

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

在谷歌标题部分的 更多选项中,它看起来像一个正常的标签,但是点击它不会得到重定向,而是打开一个菜单。一般来说

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

它通常会跳转到‘ more. php’而不会触发 show_more_menu(),但是我已经在这个页面中显示了一个菜单。如何做像 谷歌

639147 次浏览

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.

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>

You can even try below option:

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

Use following code to show menu instead go to href addres

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>

1) Link to work
<a href="#" onClick={this.setActiveTab}>
...View Full List
</a>
setActiveTab = (e) => {
e.preventDefault();
console.log(e.target);
}

One more solution that prevents default action even if the javascript function returns any value.

<a href="www.any-website.com" onclick='functionToRun();return false;'>