Javascript 如何在变量jquery中存储html结构

Javascript 如何在变量jquery中存储html结构,javascript,jquery,Javascript,Jquery,请参阅以下代码 <div class="test" style="color:red">1</div> <div class="test" style="color:blue">2</div> <div class="test" style="color:green">3</div> <script> $(".test").each(function(){ var otext='<div clas

请参阅以下代码

<div class="test" style="color:red">1</div>
<div class="test" style="color:blue">2</div>
<div class="test" style="color:green">3</div>
<script>
    $(".test").each(function(){
var otext='<div class="test" style="color:'+$(".test").css("color")+';">'+$(".test").text()+'</div>';
    });
</script>
1
2.
3.
我需要将这个html结构保存在javascript变量中。所以我使用了下面的代码

<div class="test" style="color:red">1</div>
<div class="test" style="color:blue">2</div>
<div class="test" style="color:green">3</div>
<script>
    $(".test").each(function(){
var otext='<div class="test" style="color:'+$(".test").css("color")+';">'+$(".test").text()+'</div>';
    });
</script>

$(“.test”)。每个(函数(){
var-otext=''+$(“.test”).text()+'';
});
但在otext中,我得到了
123
。 实际上我的代码有什么问题?如何使用jquery存储类测试的所有html结构和样式

所需输出为
var-otext=123

更新:

如果html结构是这样的,会发生什么

<div class="test" style="color:red">1<button clss="test-button" value="remove"/></div>
1

在这里,我不想保存这个div结构,因为在您的上下文中,每次变量被重新分配并重写值时,都会执行每个循环。指定为全局变量并对其进行压缩

并使用
$(this)
获取当前对象
var-otext='';
$(“.test”)。每个(函数(){
otext+=''+$(this).text()+'';
});
console.log(otext)

1.
2.

3
在您的上下文中,每次重新分配变量时,都会执行每个循环,并覆盖这些值。指定为全局变量并对其进行压缩

并使用
$(this)
获取当前对象
var-otext='';
$(“.test”)。每个(函数(){
otext+=''+$(this).text()+'';
});
console.log(otext)

1.
2.
3
在功能上

otext+='<div cl......
otext+='
在功能上

otext+='<div cl......

otext+=”您应该将html包装在一个div中,如

<div id="mydiv>
    <div class="test" style="color:red">1</div>
   <div class="test" style="color:blue">2</div>
   <div class="test" style="color:green">3</div>
</div>

您应该将html封装在一个div中,如

<div id="mydiv>
    <div class="test" style="color:red">1</div>
   <div class="test" style="color:blue">2</div>
   <div class="test" style="color:green">3</div>
</div>
您可以使用迭代并使用每个元素的属性创建字符串数组

jQuery(函数($){
var text=$(“.test”).map(函数(){
返回此.outerHTML
}).get().join(“”);
console.log(文本)
})

1.
2.
3
您可以使用每个元素的属性来迭代和创建字符串数组

jQuery(函数($){
var text=$(“.test”).map(函数(){
返回此.outerHTML
}).get().join(“”);
console.log(文本)
})

1.
2.

3
首先从每个函数中取出otext变量,然后在内部使用otext+=''进行存储首先从每个函数中取出otext变量,然后在内部使用otext+=''进行存储,谢谢。我刚刚更新了问题。请看。谢谢。我刚刚更新了问题,请看。