javascript - 无法使用jquery获取悬停的svg元素的id

标签 javascript jquery html svg

我想获取已悬停的 svg 元素(文本)的 id。 HTML:

<svg class="compass-svg" width="200" height="200">
     <text id="textN" x="93" y="55" fill="#000">N</text>
     <text id="textE" x="145" y="105" fill="#000">O</text>
     <text id="textS" x="95" y="158" fill="#000">S</text>
     <text id="textW" x="40" y="105" fill="#000">W</text>
</svg>

这是 JavaScript 代码:

$('text').hover(() => {
    //this is not working
    console.log($(this).attr('id'));

    //this is also not working
    console.log(this.attr('id'));

    //I've also tried this
    console.log(this.id);
});
例如,当我将鼠标悬停在第一个文本元素时,它应该 将“textN”写入控制台。

最佳答案

您正在使用一个箭头函数来更改其内部的范围。如果使用function关键字,则可以正常获取值:

$('text').hover(function() {
    // This will work
    console.log($(this).attr('id'));

    // This will also work
    console.log(this.id);
});
.as-console-wrapper {
  max-height: 85px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="compass-svg" width="200" height="200">
     <text id="textN" x="93" y="55" fill="#000">N</text>
     <text id="textE" x="145" y="105" fill="#000">O</text>
     <text id="textS" x="95" y="158" fill="#000">S</text>
     <text id="textW" x="40" y="105" fill="#000">W</text>
</svg>

关于javascript - 无法使用jquery获取悬停的svg元素的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60935618/

相关文章:

html - 为什么丢失的图像显示损坏的图像而不是 Chrome 中 alt 标签的文本?

javascript - Babel 在箭头函数上抛出语法错误

javascript - 如何从动态添加的字段中获取差异 - React

javascript - 破坏bootbox

php - 使用 JQuery Ajax 通过 HTTPS 发送时未收到 $_POST 变量

javascript - 使用 JSONp 的货币转换器

javascript - 如何在 JavaScript 中检测互联网速度?

javascript - 如何在Azure移动服务中实现乐观锁?

javascript - 返回顶部按钮问题(可能)?

html - 在滚动的 html 下拉列表中对齐所选元素