众所周知,a标签有一个href属性,它指定了点击a标签跳转的url:
atag.html:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>a标签测试</title>
</head>
<body>
<a href="https://www.baidu.com">点击我默认到百度首页</a>
</body>
</html>
用浏览器点击蓝链后将会跳到百度首页。补充一点,如果想点击后在新页面打开,可在a标签中添加target属性:
<a href="https://www.baidu.com" target="_blank">点击我默认到百度首页</a>
有时候我们可能需要把a标签当成一个按钮绑定onclick事件来用。
修改上面的代码,给a标签添加onclick事件:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>a标签测试</title>
<script type="text/javascript">
function getDateTime() {
alert(new Date().toLocaleString());
}
</script>
</head>
<body>
<a href="https://www.baidu.com" onclick="getDateTime()">点击我默认到百度首页</a>
</body>
</html>
这样做会有一个问题,就是点击事件弹窗显示当前时间后,页面还是会跳转到百度首页。有时候我们并不希望这样,我们只希望弹窗事件,不需要再跳转url。这种情况下有两种方法可以解决。
1.使用伪协议。 在href属性中去掉url值,添加伪协议:
<a href="javascript:void(0);" onclick="getDateTime()">点击我默认到百度首页</a>
之所以叫做伪协议,是因为href中的url是以javascript:开头的,而不是我们常见的http:这类标准协议头。类似的写法还有:
<a href="javascript:getDateTime();">点击我默认到百度首页</a>
在我的环境下,href里什么也不写也是可以阻止跳转的,但是这样并不好,包括方式一整体也不好。
2.让onclick事件返回false,阻止事件传递。比较推荐这种,因为存在你不想改变url的内容的情况,比如上古时期不支持js的浏览器,如果按照方式1来阻止href跳转,那么可能这个a标签就彻底失效了,因为这种浏览器只认href里的url。
<a href="https://www.baidu.com" onclick="getDateTime();return false;">点击我默认到百度首页</a>
还可以改变js函数,让其返回false,最后让onclick返回这个函数:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>a标签测试</title>
<script type="text/javascript">
function getDateTime() {
alert(new Date().toLocaleString());
return false;
}
</script>
</head>
<body>
<a href="https://www.baidu.com" onclick="return getDateTime();">点击我默认到百度首页</a>
</body>
</html>
这只是实现,更加深入的、原理什么的,还需要继续探索!