我想做类似的事情: disable-enable a hyperlink by clicking on radio-buttons 但是我想在多个链接上应用这个方法,所以我必须使用元素的类。 只使用“.getElementsByClassName”更改代码不起作用,我不明白为什么。 你能解释一下吗? StackoverFlow回答问题
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>
即使其他方法也没问题。
编辑:感谢各位的回答。
答案 0 :(得分:3)
getElementsByClassName
返回一个HTMLCollection,因此您必须循环遍历它并单独处理每个链接。
在这种情况下,您不再可以使用临时变量来保留已禁用的链接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'));
}
}
答案 1 :(得分:1)
请注意以下内容:
getElement s ByClassName()方法返回文档中具有指定类名的所有元素的集合,作为NodeList对象。
NodeList对象表示节点的集合。可以通过索引号访问节点。索引从0开始。
提示:您可以使用NodeList对象的length属性来确定具有指定类名的元素数,然后您可以循环遍历所有元素并提取所需的信息。
[http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp]
答案 2 :(得分:0)
这一行不起作用,因为在参数中设置哪个href of testclass是没有意义的:
link = document.getElementsByClassName('testlink').href;
实际上你不需要删除href。而不是你可以创建一个not_active类并在所有链接上切换这个类是testlink类。 (在IE11 +和其他人中工作)
.not-active {
pointer-events: none;
cursor: default;
}
jquery to toggle class(处理启用和禁用):
function disable_link(){
$(".testlink").toggleClass("not_active")
}