jQuery 如何将一个div的内容克隆到另一个div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4002671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:28:26  来源:igfitidea点击:

how to clone content of a div to another div

jquerydynamichtmlcopyclone

提问by pahnin

I want to copy the content of a selected div to another div with jquery clone. but I dont want to append it anywhere

我想使用 jquery clone 将选定 div 的内容复制到另一个 div。但我不想将它附加到任何地方

what I mean is when we make a clone of a div with jquery (correct me if i am wrong) we have to set its position and it will dynamically create a new division which is displayed.

我的意思是当我们用 jquery 克隆一个 div(如果我错了,请纠正我)我们必须设置它的位置,它会动态地创建一个显示的新分区。

but I want to get the content of a selected div and copy it to another pre-set div

但我想获取选定 div 的内容并将其复制到另一个预设 div

回答by Val

var a = $('#selector').html();
var b = $('#selector').html(a);

not sure I understood you properly but I think thats what you meant :)

不确定我是否正确理解您,但我认为这就是您的意思:)

回答by netadictos

I don't agree. Clone can save data without applying to the content.

我不同意。克隆可以保存数据而不应用到内容。

Look here:

看这里:

http://www.jsfiddle.net/dactivo/FqffM/

http://www.jsfiddle.net/dactivo/FqffM/

var mylayer=$('.hello').clone();

Here you can manage the variable "mylayer" as you want, and it's not in the DOM.

在这里你可以随意管理变量“mylayer”,它不在DOM中。

回答by Arvind Bhardwaj

$("#from").clone().appendTo($("#to"));

But it will not remove/hide the main DIV. To hide the main div, do this:

但它不会删除/隐藏主 DIV。要隐藏主 div,请执行以下操作:

$("#from").clone().appendTo($("#to"));
$("#from").remove();

回答by Andrew Conniff

$(".from").click(function () {
     $(".from").removeClass("CloneMe");
     $("#to").html('');
     $(this).addClass("CloneMe");
     $(".CloneMe").clone().appendTo("#to");

});

You can add a class on click (or other event) that is the hard coded to clone. In this example there is a list of same class names containing styled content (divs etc) - add the .CloneMe class but first remove that class to empty the div in case the user selects a different item. )to be safe remove any html as well. Then apply the class using (this) to avoid grabbing all of the items with that class name and finally append to the div. The result is the user can select any item with that class name and populate it in the container. - I imagine using a class for the container would allow you to populate it in more than one place.

您可以在单击(或其他事件)时添加一个类,该类是硬编码的克隆。在此示例中,有一个包含样式内容(div 等)的相同类名称列表 - 添加 .CloneMe 类,但首先删除该类以清空 div,以防用户选择不同的项目。) 为了安全起见,也删除任何 html。然后使用 (this) 应用类以避免抓取具有该类名的所有项目,并最终附加到 div。结果是用户可以选择具有该类名的任何项目并将其填充到容器中。- 我想为容器使用一个类可以让您在多个地方填充它。