【问题标题】:How to get full HTML code onClick using jquery如何使用 jquery 获取完整的 HTML 代码 onClick
【发布时间】:2012-05-07 16:59:44
【问题描述】:

我有下面的 HTML 代码

<a href="http://www.google.com">Google</a>

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

<a href="http://www.google.com">Google</a>

我尝试使用此方法,但我只能获取文本“Google”,无法获取锚代码。

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

当我需要 &lt;a href="http://www.google.com"&gt;Google&lt;/a&gt; 时,仅提醒 Google

【问题讨论】:

    标签: javascript jquery html innerhtml outerhtml


    【解决方案1】:

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

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

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

    【讨论】:

    • 如果你需要跨浏览器的方式获取outerHTML,可以使用这个插件:yelotofu.com/2008/08/jquery-outerhtml
    • 第二种方式可以这样使用:$(this).clone().wrap('&lt;span/&gt;').parent().html()
    • 谢谢罗伯!这样就解决了。我不知道有类似 outerHTML 的东西。
    • 谢谢大家的建议。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    相关资源
    最近更新 更多