CMR*_*CMR 5 javascript jquery clone
编辑:
现在在jsbin.com/ivukar/10上的工作示例
这是我正在尝试做的事情,总结到核心步骤,没有对你来说毫无意义的所有细节:
现在按照这些步骤,假设我们div的HTML内容是"test",我希望如下:
然而,只要我对元素的html内容进行了更改,就会发生这样的事情:例如:$('#element').html('altered');它也会改变变量的内容......
我不明白为什么它会这样做,因为变量只有在将它附加到DOM时才被引用,我不会改变变量的内容......
这是一个JsBin链接,所以你可以看到我的意思.
或者这里是示例代码:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var saved = '';
function my_clone()
{
saved = $('#el').clone();
$('#output').append("<a href='#' onclick='my_remove();'>Remove version on screen</a> ----- This removes any element with the id 'el'<br>");
}
function my_remove()
{
$('#el').remove();
$('#output').append("<a href='#' onclick='my_append();'>Append clone to body</a> ----- This takes the cloned object stored in the variable 'saved' and appends it to the html body<br>");
}
function my_append()
{
$('body').append( saved );
$('#output').append("<a href='#' onclick='my_alter();'>Alter .html() of element</a>----- This alters the html of any element with the id 'el'<br>");
}
function my_alter()
{
$('#el').html('altered');
$('#output').append("<a href='#' onclick='my_remove_again();'>Remove version on screen again</a>----- This removes any element with the id 'el'<br>");
}
function my_remove_again()
{
$('#el').remove();
$('#output').append("<a href='#' onclick='my_append_again();'>Append clone to body</a> ----- This again takes the object stored in the 'saved' variable, which is separate from the DOM and should not have been affected by the html change and appends to the html body<br>");
}
function my_append_again()
{
$('body').append( saved );
}
</script>
<style>
#el {color:red;}
</style>
</head>
<body>
<div id="el">
<div id="various">Various</div>
<div id="sub">Sub
<div id="and-sub-sub">And Sub-Sub</div>
</div>
<div id="elements">Elements</div>
</div>
<br><br>
<div id="output">
<a href="#" onclick="my_clone();">Clone</a> ------ This stores the clone into a global variable called 'saved'<br>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里哪里出错了?
谢谢.
问题在于您分配的是实际 DOM 元素saved而不是 HTML 内容。
一个老把戏:
saved = $("#el").clone().wrap('<div/>').parent().html();
Run Code Online (Sandbox Code Playgroud)
首先将克隆包装在div您返回其 HTML 的父级中。
更新了 JSBIN http://jsbin.com/ivukar/4
参考:以字符串形式获取 DOM 元素
| 归档时间: |
|
| 查看次数: |
3330 次 |
| 最近记录: |