Как я могу использовать javascript для клонирования некоторого <div>
и установить его id, отличный от оригинала. JQuery также будет приятным.
Clone <div> и изменить идентификатор
Ответ 1
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
Ответ 2
Используйте его:
JQuery
var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);
Ответ 3
У меня была та же проблема. Я решил это, установив счетчик и добавив его в ID. Надеюсь, вам это тоже поможет:
<script type="text/javascript">
var counter = 1; //Set counter
function clone(sender, eventArgs) {
var $row = $('#yourID');
var $clone = $row.clone(); //Making the clone
counter++; // +1 counter
//Change the id of the cloned elements, append the counter onto the ID
$clone.find('[id]').each(function () { this.id += counter });
}
</script>
Ответ 4
jQuery имеют метод clone()
var original = $("#original");
var newClone = original.clone();