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 阻止超鏈接跳轉的操作方法(多種寫法)的詳細內容,更多關於js超鏈接跳轉的資料請關註WalkonNet其它相關文章!

推薦閱讀: