简体   繁体   English

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

[英]Can't get id of hovered svg element using jquery

I want to get the id of the svg-element (text) which has been hovered.我想获取已悬停的 svg 元素(文本)的 id。 The HTML: 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>

This is the javascript code:这是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);
});

When I hover for example the first text element it should write 'textN' to the console.例如,当我将鼠标悬停在第一个文本元素时,它应该将“textN”写入控制台。

Use event.target.id , here is an example:使用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>

You are using an arrow function that changes scope inside it.您正在使用更改其内部范围的箭头函数。 If you use function keyword, you can get the values normally:如果使用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>

you can use this snippet with hover over and over out hope that help you您可以反复使用此代码段,希望对您有所帮助

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

  }, function () {
    // hover out
    console.log($(this).attr('id'));
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM