如何在鼠标悬停时检测 div 内的所有链接

Kev*_*ers 1 javascript addeventlistener svelte

在 Svelte 应用程序中,我试图检测用户何时将鼠标悬停在div. 我已经mouseover向 中添加了一个事件侦听器div,并且正在检查该元素是否是链接,但这太简单了:它不会检测包含 HTML 标记的链接。

示例代码,也可用作 REPL

<script>
    import { onMount } from 'svelte';
    
    let container;
    
    onMount(() => {
    container.addEventListener('mouseover', async (event) => {
            if (event.target.tagName !== 'A') return;
            console.log(event.target.attributes['href'].value);
        });
    });
</script>

<div bind:this={container}>
    <a href="https://www.example.com">Hello World</a>
    <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>
Run Code Online (Sandbox Code Playgroud)

问题在于第二个链接:将鼠标悬停在其上的目标是strong标签,而不是a标签。那么,如何可靠地检测容器内的所有链接div,而无需向每个单独的链接添加事件侦听器?

Cer*_*nce 5

从目标中,使用.closest('a')导航到封闭<a>元素(如果有)。(如果事件被分派到的元素是 an <a>,它将被返回。)

container.addEventListener('mouseover', (event) => {
    const a = event.target.closest('a');
    if (a) console.log(a.href);
});
Run Code Online (Sandbox Code Playgroud)

container.addEventListener('mouseover', (event) => {
    const a = event.target.closest('a');
    if (a) console.log(a.href);
});
Run Code Online (Sandbox Code Playgroud)
container.addEventListener('mouseover', (event) => {
  const a = event.target.closest('a');
  if (a) console.log(a.href);
});
Run Code Online (Sandbox Code Playgroud)