簡體   English   中英

如何使用jquery在鼠標懸停時找到當前元素文本

[英]How can I find current element text on mouseover using jquery

這是我的代碼

<!DOCTYPE html>
<html>
<body>

<svg id="a" height="210" width="400">
  <path id="b" d="M150 0 L75 200 L225 200 Z" />
</svg>

</body>
</html>

當鼠標從b懸停時,我想要該代碼(path id =“ b” d =“ M150 0 L75 200 L225 200 Z”)。如何使用jquery進行獲取?

您可以使用externalHTML

var path = $("#b")[0].outerHTML; // <path id="b" d="M150 0 L75 200 L225 200 Z"></path>

然后將其與懸停相結合:

$("#b").hover(function() {
    console.log($(this)[0].outerHTML);
});

工作實例

如前所述,這在IE中不起作用,因為它不符合規范 您可以通過以下方法解決此問題:克隆<path>元素,將其附加到HTML主體以使其成為DOM的一部分,然后從那里獲取呈現的HTML。
注意:這將無法正確表示 HTML,因為它與上下文無關。 例如,它包含xmlns ,但是由於它是一個jQuery對象,因此您可以根據自己的喜好對其進行修改:

$("#b").hover(function() {
    // Create a clone of the <path>
    var clone = $(this).clone();
    // Append it to the <body>
    clone.appendTo("body");
    // Wrap it in a containing <div> ... you'll see why in a minute
    clone.wrap("<div>");
    // Now we grab the innerHTML of that containing <div> - outerHTML won't work
    console.log(clone.parent().html());
    // Prints: <path xmlns="http://www.w3.org/2000/svg" id="b" d="M 150 0 L 75 200 L 225 200 Z" /> 

    // Now remove our temporary element again...
    clone.parent().remove();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM