我正在尝试使用纯 Javascript 或简单的CSS类禁用链接之间的制表键,这会影响整个网站:
这是我想要做的
document.getElementsByTagName("a")[0].setAttribute("tabindex", "-1");
这是可以通过jquery实现的方法:
$('a').attr('tabindex', '-1');
答案 0 :(得分:3)
jQuery的$('a').attr
:
为每个匹配的元素设置一个或多个属性。
如果愿意
document.getElementsByTagName("a")[0].setAttribute
如您在此处的[0]
所见,您仅设置了 one 元素的属性。您需要改为遍历所有元素:
document.querySelectorAll('a').forEach(
a => a.setAttribute('tabindex', '-1')
);
<input placeholder="click on me, then press tab">
<a href="example.com">link</a>
<a href="example.com">link</a>
<a href="example.com">link</a>
(与之相比,完全没有Java语言:)
<input placeholder="click on me, then press tab">
<a href="example.com">link</a>
<a href="example.com">link</a>
<a href="example.com">link</a>
对于不支持NodeList.forEach
的旧浏览器,请使用polyfill或像这样调用forEach
:
Array.prototype.forEach.call(
document.querySelectorAll('a'),
function(a){ a.setAttribute('tabindex', '-1'); }
);