如何将 jQuery 对象转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/652763/
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-26 09:31:44  来源:igfitidea点击:

How do you convert a jQuery object into a string?

jquerystringification

提问by chief7

How do you convert a jQuery object into a string?

如何将 jQuery 对象转换为字符串?

回答by John Feminella

I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:

我假设您要求完整的 HTML 字符串。如果是这样的话,这样的事情就可以解决问题:

$('<div>').append($('#item-of-interest').clone()).html(); 

This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.

此处将对此进行更深入的解释,但本质上,您可以创建一个新节点来包装感兴趣的项目、执行操作、删除它并获取 HTML。

If you're just after a string representation, then go with new String(obj).

如果您只是在字符串表示之后,那么使用new String(obj).

Update

更新

I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTMLas a native property (see, for example, Firefoxand Internet Explorer), so you can do:

我在 2009 年写了原始答案。截至 2014 年,大多数主要浏览器现在都支持outerHTML作为本机属性(例如,参见FirefoxInternet Explorer),因此您可以执行以下操作:

$('#item-of-interest').prop('outerHTML');

回答by nickh

With jQuery 1.6, this seems to be a more elegant solution:

使用 jQuery 1.6,这似乎是一个更优雅的解决方案:

$('#element-of-interest').prop('outerHTML');

回答by mppfiles

Just use .get(0) to grab the native element, and get its outerHTML property:

只需使用 .get(0) 获取原生元素,并获取其 outerHTML 属性:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

回答by Alex Rockwell

Can you be a little more specific? If you're trying to get the HTMLinside of a tag you can do something like this:

能具体一点吗?如果您尝试在标签中获取HTML,您可以执行以下操作:

HTML snippet:

HTML 片段:

<p><b>This is some text</b></p>

jQuery:

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>

回答by crystalh

The best way to find out what properties and methods are available to an HTML node (object) is to do something like:

找出 HTML 节点(对象)可用的属性和方法的最佳方法是执行以下操作:

console.log($("#my-node"));

From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:

从 jQuery 1.6+ 开始,您可以使用 externalHTML 在字符串输出中包含 HTML 标签:

var node = $("#my-node").outerHTML;

回答by Max Meents

jQuery is up in here, so:

jQuery 就在这里,所以:

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

Return all that HTML stuff:

返回所有 HTML 内容:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

回答by Johan Dettmar

This seems to work fine for me:

这对我来说似乎很好用:

$("#id")[0].outerHTML

回答by Martin Sznapka

The accepted answer doesn't cover text nodes (undefined is printed out).

接受的答案不包括文本节点(未定义被打印出来)。

This code snippet solves it:

这段代码片段解决了这个问题:

var htmlElements = $('<p><a href="http://google.com">google</a></p>??<p><a href="http://bing.com">bing</a></p>'),
    htmlString = '';
    
htmlElements.each(function () {
    var element = $(this).get(0);

    if (element.nodeType === Node.ELEMENT_NODE) {
        htmlString += element.outerHTML;
    }
    else if (element.nodeType === Node.TEXT_NODE) {
        htmlString += element.nodeValue;
    }
});

alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by St Kiss

No need to clone and add to the DOM to use .html(), you can do:

无需克隆并添加到 DOM 即可使用 .html(),您可以执行以下操作:

$('#item-of-interest').wrap('<div></div>').html()

回答by Yaron Helfer

If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:

如果您想对 HTML 元素进行字符串化以便将其传递到某个地方并将其解析回元素,请尝试为该元素创建一个唯一的查询:

// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')

// now 'e_str' is a unique query for this element that can be stringify 
var e_str = e.tagName
  + ( e.id != "" ? "#" + e.id : "")
  + ( e.className != "" ? "." + e.className.replace(' ','.') : "");

//now you can stringify your element to JSON string
var e_json = JSON.stringify({
  'element': e_str
})

than

//parse it back to an object
var obj = JSON.parse( e_json )

//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )

//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();