2011-06-09 112 views
0

我使用jQuery的html屬性來包裝一大段文字中的一些單詞,這工作正常,但如果文本中有一些html標籤,它將刪除所有標籤。有沒有辦法阻止這與HTML屬性,防止我剝去其他標籤?jQuery html屬性問題

一塊代碼

var pattern = new RegExp('('+$.unique(text.replace(/\./g, '\\.').split(" ")).join("|")+")","gi"); 

jQuery('searchin').each(function(i){ 
    var orgText = jQuery(this).text(); 
     orgText = orgText.replace(pattern, function($1){ 
     return '<b class="highlight">' + $1 + '</b>'; 
    }); 
jQuery(this).html(orgText); 
+0

請將您的代碼發送至 – 2011-06-09 11:26:21

+0

我們可以看到變量「text」的內容嗎?它是「'我的空格分隔的單詞列表」的形式嗎? – Eric 2011-06-09 12:42:59

回答

1

如果用.html()替換.text(),這樣這應該工作:

jQuery('p').each(function(i){ 
    // replaced .text() with .html() 
    var orgText = jQuery(this).html(); 
    orgText = orgText.replace(pattern, function($1){ 
     return '<strong>' + $1 + '</strong>'; 
    }); 
    jQuery(this).html(orgText); 
}); 

test case on jsFiddle

+0

我知道這個包裝,但正如你可以在我的代碼中看到的那樣,我需要將純文本打包,因此需要某些單詞。 – user759235 2011-06-09 11:58:34

+0

@ user759235,直到您更新了您的問題後才知道。現在我的答案似乎或多或少地脫節。我會尋找另一種解決方案。我記得回來做同樣的事情,所以應該有東西躺在:) – mekwall 2011-06-09 12:18:17

+0

@ user759235,更新的答案!我希望這更符合你在尋找的內容;) – mekwall 2011-06-09 12:27:36

0

你可以在一個更簡潔的寫Marcus Ekwall's answer方式:

jQuery('p').html(function(i, oldValue) { 
    return oldValue.replace(pattern, function($1) { 
     return '<strong>' + $1 + '</strong>'; 
    }); 
});