我想获得悬停的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>
使用event.target.id
,这里有一个示例:
$('text').hover((e) => {
//this is working
console.log(e.target.id);
});
<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>
您可以使用这个片段,并反复悬停,希望能帮助您
$('text').hover(function () {
// hover over
console.log($(this).attr('id'));
}, function () {
// hover out
console.log($(this).attr('id'));
}
);