【问题标题】:Store Entire HTML page into jQuery Variable将整个 HTML 页面存储到 jQuery 变量中
【发布时间】:2017-09-17 11:37:48
【问题描述】:

我有一个使用 HTML 电子邮件模板的应用程序。我想编写一个脚本来解析电子邮件模板的 HTML 并修改代码。当模板加载到页面上时,这很容易,但我想动态地执行这些操作,其中 HTML 只是来自 <textarea>(或更具体地说是 CodeMirror)的值。

<textarea> (CodeMirror) 的值如下所示:

<!doctype html>
<html>
  <head>...HEAD HTML...</head>
  <body>...BODY HTML...</body>
</html>

我试过了:

// This part works great. Stores the HTML as a varaible. 
var template_html = codeMirrorInstance.getValue(); 

// This shows the proper HTML in console as text
console.log(template_html);

// From here I can't access the HTML though
console.log($(template_html).find('body'));

但我不断收到undefined。我尝试的任何方法都不起作用...有什么想法吗?

【问题讨论】:

  • 您期望从中获得什么?现在你只有一个字符串和find() 搜索子对象/元素
  • 我将文本包装在 jQuery 参考中。通知$(template_html).find('body')。它通常是可行的(除非我遗漏了什么)。
  • 是否只是将字符串传递给引用使其成为有效的 Jquery 对象?我不这么认为
  • 您无法获取textarea 的值。阅读the manual,您会发现有一些 API 方法可以获取 CodeMirror 控件的值。
  • @DaniP 是的,我相信你可以......至少如果字符串是有效的 HTML,例如&lt;div&gt;Hello There&lt;/div&gt;

标签: javascript jquery html codemirror


【解决方案1】:

看来你可以做你想做的事。您只需要创建一个新文档,可能还需要创建第二个 jQuery 实例。

你应该看看这个:https://stackoverflow.com/a/15496537/1819684 和这个:https://stackoverflow.com/a/15479402/1819684

$(function() {
  var doctype = document.implementation.createDocumentType( 'html', '', '');
  var dom = document.implementation.createDocument('', 'html', doctype);
  
  var jq2 = jQuery(dom);
  var txt = $('textarea').val();
  
  console.log(jq2.find('html').html(txt).find('body'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<html>
  <head>...HEAD HTML...</head>
  <body>...BODY HTML...</body>
</html>
</textarea>

【讨论】:

  • 效果很好!做得好,谢谢参考。 )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2021-02-16
相关资源
最近更新 更多