2017-08-13 96 views
1

我想解析textarea中的一些html內容,並使用jquery從選定的標記中獲取值。我嘗試了下面的代碼,但沒有希望。使用jquery解析textarea中的HTML

var a = $('#a').val(); 
 
var dom_nodes = $($.parseHTML(a)); 
 
alert(dom_nodes.find('#ae').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<textarea id="a"> 
 
<?xml version="1.0" encoding="UTF-8" ?> 
 
<!DOCTYPE html> 
 
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'> 
 
<b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'> 
 
     <b:with value='&quot;body&quot;' var='selector'> 
 
     <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/> 
 
     </b:with> 
 
    </b:if> 
 
    </html> 
 
</textarea>

+0

錯誤清楚地表明你不包括jQuery庫。 – PeterKA

+0

您缺少對該頁面的jQuery庫引用。 – iMatoria

+0

甚至在包括jquery後我不在內部html –

回答

0

您可以使用DomParser得到ae節點。

var xml = document.getElementById('a').value; 
 
var parser = new DOMParser(); 
 
var xmlDoc = parser.parseFromString(xml, "text/xml"); 
 
var ae = xmlDoc.getElementById('ae'); 
 
console.log(ae.id);
<textarea id="a"> 
 
<?xml version="1.0" encoding="UTF-8" ?> 
 
<!DOCTYPE html> 
 
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'> 
 
<b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'> 
 
     <b:with value='&quot;body&quot;' var='selector'> 
 
     <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/> 
 
     </b:with> 
 
    </b:if> 
 
    </html> 
 
</textarea>

1

使用parseXML來代替。

var a = $('#a').val(); 
 
var dom_nodes = $($.parseXML(a)); 
 
alert(dom_nodes.find('#ae').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<textarea id="a"> 
 
<?xml version="1.0" encoding="UTF-8" ?> 
 
<!DOCTYPE html> 
 
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'> 
 
<b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'> 
 
     <b:with value='&quot;body&quot;' var='selector'> 
 
     <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/> 
 
     </b:with> 
 
    </b:if> 
 
    </html> 
 
</textarea>

+0

這個示例代碼..上述解決方案工作正常...但我正在處理文本框下的大量代碼。在這種情況下,它顯示沒有:( –

+0

您可以檢查控制檯的任何錯誤? – Poootaatoooo

+0

和textarea中的大多數標記沒有像xml那樣的結束標記.. –