简体   繁体   English

如何使用jquery在鼠标悬停时找到当前元素文本

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

This is my code, 这是我的代码

<!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>

When mouse is over from b, I want to that code (path id="b" d="M150 0 L75 200 L225 200 Z" ).How can I get it using jquery? 当鼠标从b悬停时,我想要该代码(path id =“ b” d =“ M150 0 L75 200 L225 200 Z”)。如何使用jquery进行获取?

You can use outerHTML : 您可以使用externalHTML

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

Then combine that with hover: 然后将其与悬停相结合:

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

Working Example 工作实例

As pointed out, this won't work in IE because it doesn't follow specification . 如前所述,这在IE中不起作用,因为它不符合规范 You can workaround this by cloning the <path> element, appending it to the HTML body to make it part of the DOM, then grabbing the rendered HTML from there. 您可以通过以下方法解决此问题:克隆<path>元素,将其附加到HTML主体以使其成为DOM的一部分,然后从那里获取呈现的HTML。
Note: This won't be an exact representation of the HTML because it's out of context. 注意:这将无法正确表示 HTML,因为它与上下文无关。 For example, it contains the xmlns , but since it's a jQuery object you can modify it how you like: 例如,它包含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