2016-03-02 14 views
1

我正在使用jquery parseHTML加載到一個DOM然後搜索關鍵字,並將周圍的標記與他們周圍的類,然後想要獲得它回到一個字符串並插入主字符串中使用jquery.parseHTML()來解析一個html字符串,更改數據並返回到字符串

var mainStr = '<div>... a long html ...</div>' 

以下是html主字符串的一部分。我有一個位置,在經過一些更改後,我會將其插入主字符串中。

var str ='<span></span> Here is <a href="someurl">xxxxx </a> a presentation of certain statements'; 

    var myHtml = $.parseHTML(str); 
    var keyword = 'presentation'. 
    $.each(myHtml, function (i, el) { 
    if (el.nodeName == '#text') { 
     var loc = el.nodeValue.search(keyword); 
    if(loc >0) 
     el.nodeValue = el.nodeValue.replace(keyword, "<span class='redColor'>" + keyword + "</span>"); 
    }); 

問題是如何得到MYHTML對象回爲一個字符串,如:

<span></span> Here is <a href="someurl">xxxxx </a> a <span class="redColor">presentation</span> of certain statements' 

插入到mainHtml字符串。

感謝您的幫助。

回答

0

您不應該使用html內容更新文本節點的節點值,它將不會被解析。

相反,您可以用更新的HTML結構替換文本節點像

var str = '<span></span> Here is <a href="someurl">xxxxx </a> a presentation of certain statements'; 
 
var keyword = 'presentation'; 
 
var myHtml = $('<div />', { 
 
    html: str 
 
}); 
 

 
myHtml.contents().contents().addBack().each(function() { 
 
    if (this.nodeType == Node.TEXT_NODE) { 
 
    var loc = this.nodeValue.search(keyword); 
 
    if (loc > 0) { 
 
     var $tmp = $('<div />', { 
 
     html: this.nodeValue.replace(keyword, "<span class='redColor'>" + keyword + "</span>") 
 
     }) 
 
     $(this).replaceWith($tmp.contents()); 
 
    } 
 
    } 
 
}) 
 
var html = myHtml.html(); 
 
$('#result').text(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"></div>