2010-04-30 11 views
2

給定了一個文本字符串,它們都與一個範圍和一個div的內部相鄰,那麼修改該文本的方法有哪些,讓周圍的HTML保持不變?例如:像使用jQuery,如何修改標籤外的文本?

$('#my-div').html(function(i, elem){blah;}); 

<div id="my-div">modify this text<span id="my-span"></span></div> 

我已經試過的事情,但是這似乎導致要刪除的跨度和新跨越添加(我注意到有些造型是失去了對跨度)。

我意識到在應用客戶端代碼之前,最好將文本字符串包裝在自己的HTML標記中,但這是我無法控制的。

回答

7

這似乎工作:

$('#my-div').contents() 
      .filter(function() { return this.nodeType == 3; }) 
      .replaceWith('new text or html'); 

的nodeType == 3是測試一個文本節點。

+0

當我看到你在這裏彈出的時候,我會寫這個東西作爲正確的解決方案。太好了! – 2010-04-30 05:01:13

0

而不是修改它的HTML字符串,修改它的DOM樹,找到頂級文本節點,並與他們做。

+0

這很有道理,但是如何將文本隔離爲某種對象? – 2010-04-30 04:10:50

0

你可以只使用字符串替換:

HTML

<div id="my-div">modify this text <span id="my-span">or this text here</span></div> 

腳本

$('#my-div').html(function(i,html){ 
return html.replace('this text', 'some new text').replace('or this text', 'and replace this text'); 
}) 
+0

這和我之前提到過的一樣。它取代了文本,銷燬了DOM對象。 – 2010-04-30 04:14:19

+0

它在替換文本時如何銷燬DOM對象?現在,如果我添加了'.replace('','')'確定會破壞跨度,但是在這種情況下你有意這樣做。 – Mottie 2010-04-30 12:51:54

2

你嘗試過這樣的:

$(document).ready(function(){ 

    var elems = $('#myDiv *').detach(); 

    $('#myDiv').text('new texts...').append(elems); 

})​ 

快速demo

編輯

或亞歷克斯建議使用.contents()

$('#myDiv').contents() 
    .filter(function(){ 
     return this.nodeType != 1 && $.trim($(this).text()) != '';   
    }) 
    .replaceWith("I am the new text"); 
+0

再一次,這破壞了跨度,並用新的替換它們。 – 2010-04-30 04:16:29

+0

@Jacob'.detach()'不會破壞元素http://api.jquery.com/detach/ – Reigel 2010-04-30 04:22:52

+0

請參閱編輯 – Reigel 2010-04-30 04:40:39