2017-03-08 58 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]