In this tutorial, I will tell you how to disable link using javascript. As there are many ways to disable hyperlink like we can use event handler, getelmentbyid and set attribute method which is used to get and set value, attribute on any HTML element. So, following are the ways to stop the link functionality.
在本教程中,我将告诉您如何使用javascript禁用链接。 由于有许多禁用超链接的方法,例如我们可以使用事件处理程序,getelmentbyid和set attribute方法,该方法用于获取和设置任何HTML元素上的value,attribute。 因此,以下是停止链接功能的方法。
如何禁用JavaScript中的链接? (How to Disable Link in JavaScript?)
方法1:使用CSS (Method 1: Using CSS)
To disable hyperlink the main CSS property that we use is pointer events. Check the code given below.
要禁用超链接,我们使用的主要CSS属性是指针事件。 检查下面给出的代码。
index.html
index.html
<!DOCTYPE html>
<html>
<head>
<title>
Disable HTML href link using JS
</title>
<style>
a.disabled {
pointer-events: none;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:red;">
Hello World
</h1>
<a href="https://www.thecrazyprogrammer.com/" id="linkId">
LINK
</a>
<br /><br />
<button onclick="disableLink()">
disable
</button>
<p id="linkStatus" style="color:green; font-size: 20px; font-weight: bold;"></p>
</body>
</html>
<script>
let link = document.getElementById('linkId');
let down = document.getElementById('linkStatus');
function disableLink() {
link.setAttribute('class', 'disabled');
link.setAttribute('style', 'color: black;');
down.innerHTML = 'Link disabled';
}
</script>
方法2:使用函数 (Method 2: Using Function)
<a href="https://www.thecrazyprogrammer.com/" id='TheLink'>test</a>
<input type='button' value="Disable" onclick="disableLink( 'TheLink', this );">
<script type="text/javascript">
function disableLink(linkID, objButton) {
const el = document.getElementById(linkID);
if (!el.onclick) {
el.onclick = function() {
return false;
};
objButton.value = "Enable";
} else {
el.onclick = function() {
return true;
};
objButton.value = "Disable";
}
}
</script>
方法3:使用事件处理程序 (Method 3: Using Event Handler)
Event handler used to handle any action like inputting data, calling methods etc.
事件处理程序,用于处理任何操作,例如输入数据,调用方法等。
Example:
例:
<a id="openSite" href="https://www.thecrazyprogrammer.com/">open website</a>
<button onclick=disablelink('openSite')>Disable link </button>
<style>
.disabledLink
{
color: #333;
text-decoration : none;
cursor: default;
}
</style>
<script>
function disablelink(linkID)
{
var hlink = document.getElementById(linkID);
if(!hlink)
return;
hlink.href = "#";
hlink.className = "disabledLink";
}
</script>
You can replace # (hash) with javascript:void (0) event handler.
您可以将#(哈希)替换为javascript:void(0)事件处理程序。
Comment down below if you have queries or know any other way to disable hyperlink in javascript.
如果您有疑问或知道任何其他方法来禁用javascript中的超链接,请在下面注释掉。
翻译自: https://www.thecrazyprogrammer.com/2019/11/how-to-disable-link-in-javascript.html