如何使用jquery获取完整的HTML代码onClick

Sla*_*lay 2 html javascript jquery innerhtml outerhtml

我有以下HTML代码

<a href="http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)

当我点击链接时,我希望我的字符串包含下面的完整HTML代码

<a href="http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)

我尝试使用这种方法,但我只设法得到文本"谷歌",无法获得锚码.

$('#frame').contents().find('body').on("click", "a",  function () {
    var string = $(this).html();
    alert(string);
});
Run Code Online (Sandbox Code Playgroud)

字符串警报仅Google在我需要时<a href="http://www.google.com">Google</a>.

Rob*_*b W 7

使用this.outerHTML或将元素包装在容器中,并.html()在该容器上使用.

$('#frame').contents().find('body').on("click", "a",  function () {
    var string = this.outerHTML;
    alert(string);
});
Run Code Online (Sandbox Code Playgroud)

我更喜欢outerHTML,但Firefox最近才增加了对它的支持.因此,考虑到这些浏览器,可能首选第二种方法.

  • 如果你需要一种跨浏览器的方式来获取`outerHTML`,你可以使用这个插件:http://www.yelotofu.com/2008/08/jquery-outerhtml/ (2认同)
  • 第二种方式可以使用如下:`$(this).clone().wrap('<span />').parent().html()` (2认同)