2017-04-20 118 views
0

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

<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。没有我尝试的工作...任何想法?

+0

那你期望从获得?现在你只是有一个字符串和'find()'搜索子对象/元素 – DaniP

+0

我正在将文本包装到jQuery引用中。注意'$(template_html).find('body')'。它通常是可操作的(除非我失去了一些东西)。 – DigitalMC

+0

只是将字符串传递给引用使其成为有效的Jquery对象?我不这么认为 – DaniP

回答

3

看来你可以做你想做的事情。您只需创建一个新文档,并可能创建一个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>

+0

工作完美!很好,谢谢参考。 ) – DigitalMC