将 onmouseover function() 附加到页面中的所有 href 和 src 以访问它们?

Attach onmouseover function() to all hrefs and srcs in page to access them?

我想通过简单地附加 onmouseover = 函数来访问 href 和 src 链接。这是我尝试的代码:

HTML

<p><a href="https://dannychoo.com/en/instagram/p/BYnMQSpBcmY">Lass</a></p>
<a href="https://developer.mozilla.org">interest</a>
<p><a src="https://mirai-instagram-images.s3.ap-northeast-1.amazonaws.com/dannychoo/17897602822049811/21296657_120344735358000_817812329218441216_n.jpg">stuff</img></p>

Javascript:

document.querySelectorAll("a").onmouseover = function() {
let g, i; 
g = document.querySelectorAll("a").getAttribute("href")
for (i = 0; i < g.length; i++) {
location.assign(g[i]);
      }
 } 

感谢您的帮助。

假设你想获取这些属性而不考虑标签类型,你可以使用querySelectorAll查询多个选择器。您还可以使用 forEach.

遍历结果

您可以使用 CSS 按属性定位元素,您可以阅读更多相关信息 here

现代浏览器支持循环 querySelectorAll 结果,但如果您需要旧浏览器支持 check out this article for alternatives

var links = document.querySelectorAll("[src], [href]");
links.forEach(link => {
  link.addEventListener("mouseover", e => {
    const href = e.target.href;
    const src = e.target.getAttribute("src");
    if (src) console.log(src);
    if (href) console.log(href);
  });
});
<p><a href="https://dannychoo.com/en/instagram/p/BYnMQSpBcmY">Lass</a></p>
<a href="https://developer.mozilla.org">interest</a>
<p><img src="https://mirai-instagram-images.s3.ap-northeast-1.amazonaws.com/dannychoo/17897602822049811/21296657_120344735358000_817812329218441216_n.jpg">stuff</p>

Fiddle

试试下面的代码片段。 document.querySelectorAll returns 一个数组,所以你需要遍历它来附加事件。

let elements = document.querySelectorAll("a")

elements.forEach(element => {
    element.addEventListener("mouseenter", function() {
        console.log(element.href);
        console.log(element.getAttribute('src'));
         } )
});
 <p><a href="https://dannychoo.com/en/instagram/p/BYnMQSpBcmY">Lass</a></p>
<a href="https://developer.mozilla.org">interest</a>
<p><a src="https://mirai-instagram-images.s3.ap-northeast-1.amazonaws.com/dannychoo/17897602822049811/21296657_120344735358000_817812329218441216_n.jpg">stuff</img></p>

let elements = document.querySelectorAll("a")

elements.forEach(element => {
  element.addEventListener("mouseenter", function() {
    console.log(element.href);
    console.log(element.getAttribute('src'));
  })
});