如何使用 onclick
函数连接页面上的每个链接。
例如我有:
<a href="http://www.something.com">Some text</a>
<a href="http://www.somethingmore.gov">Secret</a>
。 当我首先单击链接进行确认时,我希望这些链接与 body 负荷显示上的 onclick 函数连接。
最佳答案
使用document.querySelectorAll
。这将给出所有a
标签的集合。然后迭代它并添加事件监听器。 test
是一个虚拟函数,您可以用其他函数替换它
function test() {
console.log(" Test")
}
document.querySelectorAll("a").forEach(function(item) {
item.addEventListener('click', function(e) {
e.preventDefault();
test();
})
})
<a href="http://www.something.com">Some text</a>
<a href="http://www.somethingmore.gov">Secret</a>
关于javascript - 将函数与链接连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570107/