programing

jquery clone div 및 특정 div 뒤에 추가

javajsp 2023. 9. 26. 22:01

jquery clone div 및 특정 div 뒤에 추가

enter image description here

위의 사진에서 id #car2로 div를 복제하여 id #car5로 시작하는 마지막 div 뒤에 추가하고 싶습니다.내가 어떻게 그럴 수 있을까?감사해요.

이것이 내 시도 코드입니다.

$("div[id^='car']:last").after('put the clone div here');

clone을 사용한 다음 각 div에는 car_well 클래스가 있으므로 insertAfter를 사용하여 마지막 div 뒤에 삽입할 수 있습니다.

$("#car2").clone().insertAfter("div.car_well:last");

이거 한번 해보세요.

$("div[id^='car']:last").after($('#car2').clone());

jQuery의 기능을 사용하여 할 수 있습니다. Accepted answer는 괜찮지만 제가 대안을 제공하고 있습니다. 사용할 수 있지만 아래와 같이 html을 약간 변경할 수 있는 경우에만 작동합니다.

$(document).ready(function(){
    $('#clone_btn').click(function(){
      $("#car_parent").append($("#car2").clone());
    });
});
.car-well{
  border:1px solid #ccc;
  text-align: center;
  margin: 5px;
  padding:3px;
  font-weight:bold;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="car_parent">
  <div id="car1" class="car-well">Normal div</div>
  <div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>
  <div id="car3" class="car-well">Normal div</div>
  <div id="car4" class="car-well">Normal div</div>
  <div id="car5" class="car-well">Normal div</div>
</div>
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>

</body>
</html>

이것은 정본이 순서대로 되어 있으면 아주 좋습니다.템플릿으로 새 개체를 만들어야 하는 상황이 발생할 경우, 저는 보통 템플릿 디브를 숨겨진 스토리지 디브로 래핑하고 다음 기술을 적용하는 clone()과 함께 jquery의 html()을 사용합니다.

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

언급URL : https://stackoverflow.com/questions/8707756/jquery-clone-div-and-append-it-after-specific-div