简体   繁体   English

我可以克隆、编辑和附加 div 吗?

[英]Can I clone, edit and append a div?

I'm trying to find out if it's possible to clone an HTML div with JS, edit it and append it again as a new element.我正在尝试找出是否可以使用 JS 克隆 HTML div,对其进行编辑并将其作为新元素再次附加。 So my source is, for example, this code here:所以我的来源是,例如,这里的代码:

<div class="wrapper">
    <div class="element">
        <input id="test--1" value="ABC"/>
    </div>
</div>

After copying this element, I need to find a way to change the attribute id of the new cloned input, clear the input value and paste it again in the wrapper so that it looks like this at the end:复制这个元素后,我需要想办法改变新克隆输入的属性 id,清除输入值并再次粘贴到包装器中,使其最后看起来像这样:

<div class="wrapper">
    <div class="element">
        <input id="test--1" value="ABC"/>
    </div>
    <div class="element">
        <input id="test--2" value=""/>
    </div>
</div>

Does that make sense to you?这对你有意义吗? If yes, how can I get this done?如果是,我该如何完成? Or is it better to assign the content to a variable to append it?还是将内容分配给变量以附加它更好? I'm looking for the best way here and maybe my idea is a solution too.我在这里寻找最好的方法,也许我的想法也是一个解决方案。

You can use pure JavaScript to do this by just cloning the .element div using thecloneNode() method, assign new id and value to the clone div and finally append it back to the document using the insertBefore() method like this:您可以使用纯 JavaScript 执行此操作,只需使用cloneNode()方法克隆.element div,为克隆 div 分配新的 id 和值,最后使用insertBefore()方法将其附加回文档,如下所示:

 let x = document.querySelector(".element"); let y = x.cloneNode(true); y.children[0].id = "test--2"; y.children[0].defaultValue = ""; x.parentNode.insertBefore(y, x.nextSibling);
 <div class="wrapper"> <div class="element"> <input id="test--1" value="ABC"/> </div> </div>

JSFiddle with the above code: https://jsfiddle.net/AndrewL64/jvc7reza/18/ JSFiddle 上面的代码: https ://jsfiddle.net/AndrewL64/jvc7reza/18/

Based on this answer you could do like:基于这个答案,你可以这样做:

 $('#cloneBtn').on('click', function() { // get the last input having ID starting with test-- var $inp = $('[id^="test--"]:last'); // Or use :first if you need // Get parent element var $div = $inp.closest('.element'); // Create clone var $div_clone = $div.clone(); // Retrieve number from ID and increment it var num = parseInt($inp.prop("id").match(/\d+/g), 10) + 1; // Generate new number and assign to input $div_clone.find('[id^="test--"]').prop({id: 'test--' + num, value: ''}); // Insert cloned element $div.after($div_clone); // Or use .before() if you need });
 .element { padding: 10px; outline: 2px solid #0bf; }
 <button id="cloneBtn">CLICK TO CLONE</button> <div class="wrapper"> <div class="element"> <input id="test--1" value="ABC" /> </div> </div> Once done inspect the input elements to see the new IDs <script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Scrambled elements, retrieve highest ID, increment, clone, append.加扰元素、检索最高 ID、递增、克隆、追加。

If your numbered IDs are scrambled, we first need a way to retrieve the highest ID number.如果您的编号 ID 被打乱,我们首先需要一种方法来检索最高 ID 号。 Here's an implementation in pure JavaScript:这是纯 JavaScript 的实现:

 function cloneElement () { const inpAll = document.querySelectorAll('[id^="test--"]'); if (!inpAll.length) return; // do nothing if no elements to clone const maxID = Math.max.apply(Math, [...inpAll].map(el => +el.id.match(/\d+$/g)[0])); const incID = maxID + 1; const element = document.querySelector('.element'); // Get one for cloning const eleClone = element.cloneNode(true); const inpClone = eleClone.querySelector('[id^="test--"]'); inpClone.id = 'test--'+ incID; inpClone.value = incID; // just for test. Use "" instead document.querySelector('.wrapper').prepend(eleClone); } document.querySelector('#cloneBtn').addEventListener('click', cloneElement);
 .element { padding: 10px; outline: 2px solid #0bf; }
 <button id="cloneBtn">CLICK TO CLONE</button> <div class="wrapper"> <div class="element"> <input id="test--1" value="1" /> </div> <div class="element"> <input id="test--23" value="23" /> </div> <div class="element"> <input id="test--7" value="7" /> </div> </div> Once done inspect the input elements to see the new IDs <script src="https://code.jquery.com/jquery-3.1.0.js"></script>

I don't know what data you know, why you want to do such a thing but it can be done :-)我不知道你知道什么数据,为什么你想做这样的事情但它可以做到:-)

One way is like that:一种方法是这样的:

const elemToCopy = document.getElementById("test--1").parentNode; // I assume you know id
const copiedElem = elemToCopy.cloneNode(true);

const newInput = copiedElem.querySelector("#test--1");
newInput.id = "test--2";
newInput.value = "";

elemToCopy.parentNode.append(copiedElem);

Let me know in a comment if something is not clear :-)如果有不清楚的地方,请在评论中告诉我:-)

Yes, use jQuery's .clone() .是的,使用 jQuery 的.clone()

Here is an example that might be relevant to your situation:这是一个可能与您的情况相关的示例:

let newElement = $('.element').clone();

newElement.find('input').attr('id', 'test--2').val('');

$('.wrapper').append(newElement);

Explanation解释

In the first line, we created a new cloned element by using jQuery clone() .在第一行中,我们使用 jQuery clone()创建了一个新的克隆元素。

Then, we found it's child input, changed it's ID and reset the val() .然后,我们找到了它的子输入,更改了它的 ID 并重置了val()

Finally, we found the .wrapper element and appended the new cloned element to it.最后,我们找到了.wrapper元素并将新克隆的元素附加到它上面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM