2017-03-08 41 views
1

我有一點點困難試圖切換2個元素周圍的JQuery時,他們是在一個字符串變量。jquery切換元素,雖然他們在一個變量內

如:

var myString = 
       "<div class='chatMessage'>Something here 
       <div class='test'>My test</div> 
       <div class='anotherTest'> the other test</div> 
       Something there 
       </div>"; 

我想是圍繞切換兩個班,製作「anotherTest」是盈方的「測試」。

我試過到目前爲止是:

var myString = 
       "<div class='chatMessage'>Something here 
       <div class='test'>My test</div> 
       <div class='anotherTest'> the other test</div> 
       Something there 
       </div>"; 

var div1 = myString.filter('.test'); 
var div2 = myString.filter('.anotherTest'); 

var tdiv1 = div1.clone(); 
var tdiv2 = div2.clone(); 

myMessage = div1.replaceWith(tdiv2); 
myMessage = div2.replaceWith(tdiv1); 

不過,我收到以下錯誤

t.replace is not a function 

我不知道我怎麼會能夠實現切換兩個div左右,而仍然存儲在變量中,然後再顯示給用戶?

+0

不是應該變種DIV1 = myString.filter( '試驗'); ? – CaptainHere

+0

爲什麼你想在字符串中切換它們? –

+0

我的代碼中沒有看到「t」或「.replace」。 – evolutionxbox

回答

2

你加入,這需要通過直接字符串操作來完成的約束使事情對自己更難。 HTML意味着被渲染到DOM中 - 並且因爲這是一個「文檔對象模型」,所以它可以更好地將文檔建模爲對象。

jQuery看起來可能有點老套,但其整體目的是更容易查詢DOM,所以它在這裏運行良好。所有你需要做的就是解析字符串,查詢你想要移動的節點,並將它插入你想要的元素之前。您可以使用$.fn.html()獲取HTML,或者如果要將其插入到頁面的某個位置,您可以將其作爲元素保留。

var $el = $(myString); 
$('.anotherTest', $el).insertBefore($('.test', $el)); 
var myMessage = $el.html(); 

jsfiddle here

+0

這正是我正在尋找的。這使我可以在顯示字符串之前操作字符串。 – killstreet

0

試試這個。只需拆分字符串"</div>",它將創建一個拆分內容數組,然後將"</div>"重新添加到每個拆分字符串(這將在拆分過程中使用)。 然後重新組裝。

https://jsfiddle.net/8a4wgn7k/

var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>"; 


var res = myString.split("</div>"); 
res[0] +="</div>"; 
res[1] +="</div>"; 
var switchedString=res[1]+res[0]