【问题标题】:Conversion of html object to string failed using jquery使用 jquery 将 html 对象转换为字符串失败
【发布时间】:2016-11-18 07:24:12
【问题描述】:

试图将我解析的 html 对象转换为字符串,但它只返回标题。希望能在这方面提供一些意见

var html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
html = $.parseHTML(html);
//do something here
//after parse to object, revert back to string
htmlString = $(html).prop('outerHTML'); //this is not working

console.log(htmlString);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【问题讨论】:

  • 为什么不附加到正文?
  • 你想要除了 HTML 标签之外的所有字符吗?
  • @ObjectManipulator 我想要原始字符串,就像它第一次声明的那样
  • @guradio 那不是我想要的,我必须做点别的......
  • 你想再次使用初始的 var html 吗?这甚至没有意义。

标签: javascript jquery css type-conversion


【解决方案1】:

试试

var _html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
_html = $(_html);
htmlString = $('<div></div>').append(_html).html() ; //this should work

console.log(htmlString)

;

【讨论】:

  • 你不要跳过解析
  • 呃?选择两次??
  • 哎呀!我忘了,里面有html标签。这个答案不正确
  • 这会给你&lt;title&gt;My title&lt;/title&gt;&lt;h1&gt;hello World&lt;/h1&gt; 仍然跳过bodyhtml 标签
  • 我想要像以前一样的完整 html 字符串
【解决方案2】:

我会创建一个新元素,然后将 html 附加到它,最后打印新元素的 html。

试试这个:

var html = `<html><head><title>My title</title></head><body><h1>hello World</h1></body></html>`;

var fake_html = $( document.createElement('html'));
fake_html.html(html);

//As jQuery object, you can do whatever you want with this fake_html (here I just change the Title string)
fake_html.find('title').html("Title changed");

htmlString = fake_html.prop('outerHTML');

console.log(htmlString);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我有一串html。我将其转换为附加更多元素。我想转换回字符串以将其存储在某处。你的假 html 方法有什么帮助?
  • 检查更新。如果你想要完整的 html 作为字符串,你可以创建一个新的 'html' 元素,用字符串设置他的 html 值,用它做任何你想做的事情,最后得到他的外层 HTML。
猜你喜欢
  • 2022-07-21
  • 1970-01-01
  • 2012-05-13
  • 2013-04-15
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
相关资源
最近更新 更多