jQuery 我想将一个元素的 html 保存到一个变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8014332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:53:26  来源:igfitidea点击:

I want to save an element's html to a variable

jqueryhtml

提问by user883036

I know how to use .html() to grab the html inside of my selected element, like so:

我知道如何使用 .html() 来获取所选元素内的 html,如下所示:

<div id="outside>
    <span>hello</span>
</div>

using something like

使用类似的东西

var span = $('#outside).html();

will grab my span as the html. My problem is when I have

将抓取我的跨度作为 html。我的问题是当我有

<img id="image" src="image.png">

How can I assign the html, as a string, to a variable? Using

如何将 html 作为字符串分配给变量?使用

var image = $('#image').html() 

gives me an empty string.

给我一个空字符串。

var image = $('#image')[0]

appears to get the html I want, but its actually still an object.

似乎得到了我想要的 html,但它实际上仍然是一个对象。

回答by Keith.Abramo

Try this:

尝试这个:

var myAwesomeHTML = $('#image')[0].outerHTML

update:

更新:

$("<div></div>").append($("#image")).html()

回答by Exception

This can be easily done by wrapping an element to it and getting theparent element's HTML like this

这可以通过将元素包装到其中并像这样获取父元素的 HTML 来轻松完成

 var a=$('#image');
 a.wrap('<span class="ab"></span>');
 var htmlOfEle=$('.ab').html();

Here is the fiddle.. http://jsfiddle.net/CR2PD/2/It may help you..

这是小提琴.. http://jsfiddle.net/CR2PD/2/它可能会帮助你..

Edit:

编辑:

Without using jQuery, you can do like below

不使用 jQuery,你可以像下面这样

var el = document.getElementById('image');
html = el.outerHTML

回答by Francis

outerHTML is not supported in firefox. You could try something like this :

firefox 不支持outerHTML。你可以尝试这样的事情:

var image = document.getElementById("image");

alert(outerHTML(image));

function outerHTML(elem){
    if (typeof elem.outerHTML !== "undefined")
    {
        return elem.outerHTML;
    }

    var s = "<" + elem.nodeName.toLowerCase();

    for (var i = 0; i < elem.attributes.length; i++)
    {
        s += " " + elem.attributes[i].name + '"' + escape(elem.attributes[i].value) + '"';
    }

    if (elem.hasChildNodes())
    {
        return s + ">" + elem.innerHTML + "</" + elem.nodeName + ">";
    }

    return s + " />";
}

回答by Marcelo Assis

Try creating this function into Jquery core:

尝试在 Jquery 核心中创建这个函数:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}


$('#myTag').outerHTML();

Source here.

来源在这里

回答by Joe C.

To set the html for an element, you just use the .html() function, but pass it the string you want to set the html as: $('#image').html('<span>Hello</span>')

要为元素设置 html,只需使用 .html() 函数,但将要设置 html 的字符串传递给它:$('#image').html('<span>Hello</span>')