简体   繁体   English

如何将 jQuery object 转换为字符串?

[英]How do you convert a jQuery object into a string?

How do you convert a jQuery object into a string?如何将 jQuery object 转换为字符串?

I assume you're asking for the full HTML string.我假设您要的是完整的 HTML 字符串。 If that's the case, something like this will do the trick:如果是这样的话,这样的事情就可以解决问题:

$('<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) .如果您只是在字符串表示之后,那么 go 和new String(obj)

Update更新

I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer ), so you can do:我在 2009 年写了原始答案。截至 2014 年,大多数主流浏览器现在都支持outerHTML作为本机属性(例如,参见 FirefoxInternet Explorer ),所以你可以这样做:

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

With jQuery 1.6, this seems to be a more elegant solution:使用 jQuery 1.6,这似乎是一个更优雅的解决方案:

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

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);

Can you be a little more specific?你能再具体一点吗? If you're trying to get the HTML inside 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>

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+ 起,您可以使用 outerHTML 在字符串 output 中包含 HTML 标记:

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

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

This seems to work fine for me:这对我来说似乎很好用:

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

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>

No need to clone and add to the DOM to use.html(), you can do:无需克隆并添加到 DOM 即可使用.html(),您可以这样做:

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

It may be possible to use the jQuery.makeArray(obj) utility function:可以使用jQuery.makeArray(obj)实用程序 function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];

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();
new String(myobj)

If you want to serialize the whole object to string, use JSON .如果要将整个 object 序列化为字符串,请使用JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM