我想获取已悬停的 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/