获取所单击元素的HTML内容

get the HTML content of clicked element jQuery

本文关键字:HTML 内容 元素 单击 获取      更新时间:2023-09-26

我有以下HTML

<label class="editable" id="user_info_username">Hai world...</label>

现在点击函数,我需要点击元素的内容。

i tried

$(".editable").live("click",function(){
alert($(this).html())  //returns Hai world...
});

但是我需要HTML内容

so <label class="editable" id="user_info_username">Hai world...</label>

克隆已单击的元素,将其包装在<div>中,然后请求该元素的HTML -类似于:

var html = $('<div/>').append($(this).clone()).html();

工作演示:http://jsfiddle.net/f88kj/

我以前也写了一个插件,在https://stackoverflow.com/a/6509421/6782

(function($) {
    $.fn.outerhtml = function() {
        return $('<div/>').append(this.clone()).html();
    };
})(jQuery);

如果我没理解错的话你需要jQuery的。outerhtml属性

http://forum.jquery.com/topic/jquery-outerhtml-for-jquery

你要找的是outerHTML之类的东西。不幸的是,Firefox目前不支持它,所以在这里寻找一个解决方案:我如何在Firefox中使用OuterHTML ?

也许您可以使用包装器,如下所述:

html:

<div class="YourHtmlContent">
<label class="editable" id="user_info_username">Hai world...</label>
</div>

和js:

$(".editable").live("click",function(){
alert($('.YourHtmlContent').html())
});

使用jQuery.clone()的答案是最好的IMO,但我在这里添加这个,因为它是另一种方式,可能对其他人有帮助。

你可以得到任何父div的html -这是一个问题,因为可能有兄弟也会返回。

一样:

alert($(this).parent().html()); //will return siblings too
http://jsfiddle.net/Qg9AL/