小编给大家分享一下JavaScript如何阻止超链接跳转,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
通过JavaScript,我们可以阻止超链接的跳转。
方法如下:
(1)操作超链接的 href 属性
写法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="javascript:void(0);" rel="external nofollow" >超链接</a>
</body>
</html>
写法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="javascript:;" rel="external nofollow" >超链接</a>
</body>
</html>
点击链接,链接并不会进行跳转。
(2)阻止链接的默认行为
写法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >百度</a>
<script>
var link = document.querySelector("a");
link.addEventListener('click',function(e){
e.preventDefault();
})
</script>
</body>
</html>
写法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >百度</a>
<script>
var link = document.querySelector("a");
link.onclick = function (e) {
return false;
}
</script>
</body>
</html>
以上是“JavaScript如何阻止超链接跳转”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!