gpt4 book ai didi

javascript - 如何防止 jQuery prepend() 删除 HTML?

转载 作者:太空狗 更新时间:2023-10-29 13:56:55 24 4
gpt4 key购买 nike

当我单击 anchor 标记时,图像从 div#left 移动到 div#right。我想要复制图像。这是 prepend() 的默认行为吗?我怎样才能避免这个问题?

图像只是一个有很多 child 的大 div 的占位符。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="Scripts/JavaScript.js"></script>
</head>
<body>
<div id="left" style="float:left">
<img src="Images/Rooms/K1.jpg" alt="Alternate Text" height="200" width="200"/>
</div>
<div id="right" style="float:right"></div>
<a id="addImageToRight" href="#">Add Image toRight</a>
</body>
</html>

jQuery 是:

$(document).ready(function () {
$("#addImageToRight").click(function () {
var $image = $("#left img");
var imgCopy = $image;
$("div#right").prepend(imgCopy);
});
});

最佳答案

Is this the default behaviour of prepend()?

是的。将 DOM 节点放在文档中的某个位置需要将其从文档中已有的位置移除。它不能同时存在于两个地方。

var imgCopy = $image;

$image 复制到imgCopy。该值是对该对象的引用。 (在 JavaScript 中,变量只能保存对对象的引用)。

How to avoid this problem?

创建 DOM 节点的副本。在 jQuery 对象上调用 .clone() 并在返回值前添加。

var imgCopy = $image.clone();

关于javascript - 如何防止 jQuery prepend() 删除 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com