将 jQuery 对象打印为 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1859385/
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
Print out jQuery object as HTML
提问by David Hellsing
Is there a good way of printing out a jQuery object as pure HTML?
有没有一种将 jQuery 对象打印为纯 HTML 的好方法?
ex:
前任:
<img src="example.jpg">
<script>
var img = $('img').eq(0);
console.log(img.toString());
</script>
toString()
doesn't work this way. I need the HTML equivalent string , i.e:
toString()
不能这样工作。我需要 HTML 等效字符串,即:
<img src="example.jpg">
<img src="example.jpg">
采纳答案by andres descalzo
If you need to print the object in HTML format, use this extension outerHTMLor this outerHTML.
如果您需要以 HTML 格式打印对象,请使用此扩展程序outerHTML或此outerHTML。
Update
更新
Update the link and include the code for second link:
更新链接并包含第二个链接的代码:
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
回答by bmarti44
$('img')[0].outerHTML
$('img')[0].outerHTML
will give you the HTML of the first img on the page. You will then need to use a for loop to get the HTML of all the images, or put an ID on the image and specify it only in the jQuery selector.
将为您提供页面上第一个 img 的 HTML。然后您需要使用 for 循环来获取所有图像的 HTML,或者在图像上放置一个 ID 并仅在 jQuery 选择器中指定它。
回答by Magnar
You could wrap it and then use html:
你可以包装它,然后使用 html:
var img = $('img').eq(0);
console.log(img.wrap("<span></span>").parent().html());