如何用JavaScript获取点击锚点的data-id并跳转至href路径
问题解决方案
问题根源
你当前代码里的body.querySelector('.link')方法只会返回页面中第一个匹配.link选择器的元素,所以不管点击哪个锚点,拿到的都是第一个<a>标签。另外,全局阻止默认行为也会影响其他元素的正常交互,需要优化。
修正后的代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <a href="2.html?a=1" data-id="1" class="link">One</a> <a href="2.html?a=2" data-id="2" class="link">Two</a> <a href="2.html?a=3" data-id="3" class="link">Three</a> <script> const body = document.querySelector('body'); body.onclick = (e) => { // 仅处理带有.link类的锚点元素 if (e.target.matches('.link')) { e.preventDefault(); // 阻止默认跳转 const clickedLink = e.target; const dataId = clickedLink.dataset.id; const targetHref = clickedLink.href; // 打印data-id,可根据需求做其他处理 console.log('当前点击的data-id:', dataId); // 手动跳转到目标路径 window.location.href = targetHref; } } </script> </body> </html>
关键说明
e.target:事件对象的target属性指向实际被点击的DOM元素,这样就能准确获取当前点击的锚点,而不是固定取第一个。matches('.link'):用来判断点击的元素是否是我们要处理的锚点,避免处理body内其他元素的点击事件。dataset.id:这是获取data-*属性的标准方法,等价于getAttribute('data-id'),写法更简洁。- 条件阻止默认行为:只有点击锚点时才阻止默认跳转,其他元素的点击不受影响。
内容的提问来源于stack exchange,提问作者DCodeMania
相关产品推荐
相关产品推荐

