【问题标题】:Attach onmouseover() function to each href in all <a> anchor tags, if anchor tags have <img> child elements?将 onmouseover() 函数附加到所有 <a> 锚标记中的每个 href,如果锚标记具有 <img> 子元素?
【发布时间】:2021-06-20 15:22:24
【问题描述】:

HTML 代码:

<p><div>
<a href="https://www.digi.com.my/chat-with-us">
<img src="">
</a></p><div>

<p><a href="https://unifi.com.my/support/contact-us"><img src="">
    </a></p>
  </div>

<p><a>Hey Man 
</a>
</p>

<div>
<p><a href="https://unifi.com.my/support/contact-us">Hey man
</a>
</p></div>                                                                                                    

Javascript 代码:

let tar = document.querySelectorAll("a[href] > img[src]");

tar.forEach(tarG => {
tarG.addEventListener("mouseover", e => {
    const ahref = e.target.a[href];
  if (a[href]) location.assign(a[href]);
   });
}); 

首先,我想将 onmouseover() 函数附加到 HTML 页面中所有带有子标记的锚标记中的所有 href 链接。

我的意图是 onmouseover() 函数只激活 href,当鼠标光标移动到包含 img 子标签的锚标签上时。否则,如果没有img子标签,onmouseover()函数不会激活href。

我的代码哪里出错了?感谢您提供所有有用的答案

【问题讨论】:

    标签: anchor href addeventlistener onmouseover queryselector


    【解决方案1】:

    用这个替换你的 JavaScrip 代码:

    const tars = document.querySelectorAll('a > img');
    
    tars.forEach(tar => {
      const a = tar.parentNode;
    
      a.addEventListener('mouseover', /* Your mouseover handler goes here */);
    });
    

    【讨论】:

    • "你的鼠标悬停处理程序在这里"我可以看看那个代码吗?
    • 我不知道您在鼠标悬停时要做什么。你给我看!
    • 我希望能够使用 img 子元素激活这些锚标记。我的鼠标悬停功能:("mouseover", , e =&gt; { const a = e.target.a; if (a) location.assign(a); }); });
    • 这就是我要说的:我们不知道“使用 img 子元素激活那些锚标签”是什么意思。此外,您正在使用标识符location,而没有显示或告诉我们它是什么。您可能对e.target.href 感兴趣。
    【解决方案2】:
    const tars = document.querySelectorAll("a > img"); 
    tars.forEach(tar => {                                                                                   
    const a = tar.parentNode;`   
    
    a.addEventListener("mouseover", e => {
        const ahref = e.target.tar;
       if (tar) location.assign(tar);     
       });
      });    
    

    像这样,@Corey?

    【讨论】:

      【解决方案3】:

      抱歉,答案含糊。在您的代码中,您正在向 img 添加事件侦听器。您需要获取 tar 的父节点,然后向其添加事件侦听器。

      //js
      x = [].slice
          .call(document.querySelectorAll("img"))
          .filter((e) => e.parentNode.tagName == "A")
          .map((e) => e.parentNode);
      console.log(x);
      //jquery
      y = $("a img").parent();
      console.log(y.toArray());
      
      //you can now add eventlisteners to x,y

      【讨论】:

      • 感谢您的回复。这是否意味着我用你的代码替换了我的整个代码,或者将你的代码添加到我的代码中?
      • 抱歉含糊其辞。在您的代码中,您正在向 img 添加事件侦听器。您需要获取 tar 的父节点,然后向其添加事件侦听器
      猜你喜欢
      • 2020-10-13
      • 2018-09-20
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2012-05-17
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多