如何使用jquery在mouseover上找到当前元素文本

时间:2015-04-26 08:23:52

标签: javascript 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结束时,我想要那个代码(路径id =&#34; b&#34; d =&#34; M150 0 L75 200 L225 200 Z&#34;)。我怎样才能得到它使用jquery?

1 个答案:

答案 0 :(得分:4)

您可以使用outerHTML

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);
});

Working Example

正如所指出的,这不会在IE中发挥作用,因为它不会跟随specification。您可以通过克隆<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();
});