EDIT:
现在的工作示例位于jsbin.com/ivukar/10 http://jsbin.com/ivukar/10
这是我正在尝试做的事情,总结为核心步骤,没有所有对您来说毫无意义的细节:
- 从 DOM 克隆现有的 div 并将该克隆存储在变量中
- 从 DOM 中删除该 div
- 将克隆的 div 添加到 DOM 中
- 更改 DOM 中 div 的 HTML 内容
- 删除 div 并再次插入克隆
现在按照这些步骤,假设我们的 div 的 HTML 内容是“test”,我期望如下:
- 将 div 存储为内容“test”的变量
- 从 DOM 中删除 Div
- Div 附加到 DOM,内容为“test”
- 页面上的 div 已更改,内容已“更改”
- 页面上的div被删除。 Div 再次附加内容“test”到正文,因为它存储在变量中,并且不应受到 DOM 更改的影响
然而,一旦我对元素的 html 内容进行更改,例如使用:$('#element').html('altered');
它也改变了变量的内容......
我不明白为什么它会这样做,因为只有在将变量附加到 DOM 时才会引用该变量,我不会更改变量的内容......
这里有一个JsBin http://jsbin.com/ivukar/1链接,这样你就可以明白我的意思。
或者这里是示例代码:
<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>
谁能告诉我这里哪里出了问题?
Thanks.
问题是你将实际的 DOM 元素分配给saved
而不是 HTML 内容。
一个老把戏:
saved = $("#el").clone().wrap('<div/>').parent().html();
首先将克隆包装在父级中div
您返回其 HTML。
更新了 JSBINhttp://jsbin.com/ivukar/4 http://jsbin.com/ivukar/4
参考:获取 DOM 元素作为字符串 https://stackoverflow.com/questions/8127091/jquery-get-dom-element-as-string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)