2008-11-18 30 views
2

我有類似這樣的標記:如何在javascript中包圍一段文本的範圍?

<p>one two three four</p> 

而且我想使用JavaScript將其轉換爲這樣的:

<p>one <span>two three<span> four</p> 

我已經偏移和段的長度我想在一個跨度來包裝,在這種情況下爲offset = 4length = 9。如果使用jQuery可以使它更容易,那更好。

回答

4

這是不是有點重複的問題Highlight a word with jQuery

JQuery search highlight plugin東西可幫助

或者,如pointed out in the same question,寫你自己的jQuery函數:
喜歡的東西(未測試的代碼,隨意編輯):

jQuery.fn.addSpan = function (elName, str, offset, length) 
{ 
    if(this.innerHTML = str) 
    { 
     return this.each(function() 
     { 
      this.innerHTML = this.innerHTML.substring(0,offset) + "<span>" + this.innerHTML.substring(offset, offset+length) + "</span>" + this.innerHTML.substring(offset+length)); 
     }); 
    } 
}; 

,你會像這樣使用它:

$("p").addSpan("one two three four", 4, 9);