2014-03-07 25 views
6

我在Google或這裏找不到任何關於此的內容。

我有一個div與它,一些文字和一些HTML這樣:

<div id="test-div"> 
    http://<strong>somewebsite.com</strong>/big/long/unfriendly/path/ 
</div> 

我想要做的,是每一個斜槓後添加<wbr>。 (因爲這個值不會換行,弄亂我的表格)。做一個簡單的替換$('#test-div').html()也將與強標籤混淆,所以這不是一個選項。

我想用$('#test-div').contents()過濾掉文本部分(遞歸)將工作。但我似乎無法編輯返回的單個位。我希望這改變http://部分:

$('#test-div').contents().first().text("something"); 

然而它什麼也沒做。我知道我有我的導航權,因爲這樣的事情:

$('#test-div').contents().first().wrap("<b></b>"); 

確實有效。

爲什麼我不能更改文本位? (一個更優雅的解決最初的問題也將是巨大的)

+4

'.text'可能只適用於元素節點。這工作正常:'$('#test-div')。contents()。first()[0] .nodeValue =「something」;'http://jsfiddle.net/2Gz8p/ –

回答

0

後來我發現我自己的答案感謝thisthis item。我現在有一個函數可以替換上下文中所有文本節點中的所有文本。它也可以將HTML插入到所述節點中。

JavaScript函數:

function recursiveReplace(node, oldValue, newValue) { 
    if (node.nodeType === 3) { // text node 
     $(node).replaceWith(node.nodeValue.replace(oldValue, newValue)); 
    } else if (node.nodeType === 1) { // element 
     $(node).contents().each(function() { 
      recursiveReplace(this, oldValue, newValue); 
     }); 
    } 
} 

//To call 
div = $('#test-div'); 
recursiveReplace(div[0], "/", "/<wbr />"); 

這解決了它的通用方式。

0

你試過

$(element).html('your content here'); 
+0

我有,但我的初始問題是我需要在文本位中替換斜線,同時保留任何html標記完好無損。 – Coo

1

使用這樣的:

$('#test-div').contents().filter(function(){ 
    return $.trim($(this).text()) == 'http://'; 
}).remove().end().prepend('something'); 

demo

,或者

$('#test-div').contents().first().remove().end().prepend("something"); 

demo

0

如何用正則表達式替換//<wbr>

$('#test-div').html($('#test-div').html().replace(/(<)?[/]/g, function($0,$1){ 
    return $1?$0:'/<wbr>'; 
})); 

/(<)?[/]/g會尋找所有的斜槓,還需要特別注意任何結束標記。

return $1?$0:'/<wbr>';會忽略</,但/<wbr>

替代任何其他/你可能要考慮關閉wbr標籤了。

0

你有沒有嘗試過這樣的事情?

$('#test-div').html().replace('/', '/<wbr>'); 
0

,因爲當你說首先它給你[object Text]和文本屬性不使用它,最簡單的解決方法是:

$("#test-div").contents()[0].textContent="Something"; 

Jsfiddle demo

相關問題