簡體   English   中英

無法使用 jquery 獲取懸停 svg 元素的 id

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

我想獲取已懸停的 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”寫入控制台。

使用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>

您正在使用更改其內部范圍的箭頭函數。 如果使用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>

您可以反復使用此代碼段,希望對您有所幫助

$('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