通过单击按钮禁用-启用超链接

disable-enable the hyperlinks by clicking on a button

我想做类似这样的东西: disable-enable a hyperlink by clicking on radio-buttons 但是我想在多个链接上应用这个方法,所以我必须使用元素的 class 。 仅使用“.getElementsByClassName”更改代码是行不通的,我不明白为什么。 你能给我解释一下吗? Whosebug 问题的答案

var link;

function disable_link() { 

document.getElementsByClassName('testlink').disabled=true;

link = document.getElementsByClassName('testlink').href;

document.getElementsByClassName('testlink').removeAttribute('href');

} 


function enable_link() { 

document.getElementsByClassName('testlink').setAttribute("href",link);

} 


</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label>
<input type="radio" name="RadioGroup1" value="radio" id="RadioGroup1_0" onchange="disable_link();" />
Disable</label>
<br />
<label>
<input type="radio" name="RadioGroup1" value="radio" id="RadioGroup1_1" onchange="enable_link();" />
  enable</label>
<br />
</p>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
</form>
</body>
</html>

其他方法也可以

编辑:感谢大家的回答。

注意以下引用中的内容:

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.

[http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp]

getElementsByClassName returns 一个 HTMLCollection,因此您必须遍历它并单独处理每个 link。

在这种情况下,您不能再使用临时变量来保持禁用 link href。简单的解决方案是将删除的 href 属性存储在相应元素的另一个属性中。

它看起来像这样:

function disable_link() {
    var links = document.getElementsByClassName('testlink');
    for (var i = 0; i < links.length; i++) {
        links[i].setAttribute('data-href', links[i].getAttribute('href'));
        links[i].removeAttribute('href');
    }
}

function enable_link() {
    var links = document.getElementsByClassName('testlink');
    for (var i = 0; i < links.length; i++) {
        links[i].setAttribute("href", links[i].getAttribute('data-href'));
    }
}

演示: http://jsfiddle.net/5z8av0xg/

此行不起作用,因为在参数中设置测试 class 的哪个 href 没有意义:

link = document.getElementsByClassName('testlink').href;

实际上您不需要删除 href。取而代之的是,您可以制作 not_active class 并在所有链接上切换此 class 是测试链接 class。 (在 IE11+ 和其他版本中工作)

.not-active {
   pointer-events: none;
   cursor: default;
}

jquery 切换 class(处理启用和禁用):

function disable_link(){    
$(".testlink").toggleClass("not_active")
}