(jQuery)将变量内容克隆到Div

时间:2018-11-12 08:39:38

标签: javascript jquery html

我有一个按钮,onClick会将内容附加到元素之前。但是,我需要将内容附加到按钮的最近的父级 div中。 (.content div)

JS Fiddle

$('#layoutTextArea').click(function(){
         var toAppend=$('#appendTextArea').children();
         toAppend.clone().insertBefore('#layoutCanvas');
});

HTML:

<div id="layoutCanvas">
  <div class="content">
      <p>
      On click of the button append within "content" div
      </p>
      <button id="layoutTextArea" class="btn btn-primary">Click Here</button>
  </div>
</div>

<div class="d-none" id="appendTextArea">
   <h1>
   Test Block
   </h1>
</div>

2 个答案:

答案 0 :(得分:0)

这是您要找的吗?

$('#layoutTextArea').click(function(){
         var toAppend=$('#appendTextArea').children();
         toAppend.clone().insertAfter($(this).parent());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="layoutCanvas">
  <div class="content">
      <p>
      On click of the button append within "content" div
      </p>
      <button id="layoutTextArea" class="btn btn-primary">Click Here</button>
  </div>
</div>

<div class="d-none" id="appendTextArea">
   <h1>
   Test Block
   </h1>
</div>

答案 1 :(得分:0)

.insertBefore()将匹配元素中的每个元素插入到目标之前。在您的代码中,目标是#layoutCanvas

将目标更改为$(this).parent()

toAppend.clone().insertAfter($(this).parent());

尽管我更喜欢使用parent()appned()

$(this).parent().append(toAppend.clone());

$('#layoutTextArea').click(function(){
     var toAppend=$('#appendTextArea').children();
     $(this).parent().append(toAppend.clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="layoutCanvas">
  <div class="content">
      <p>
      On click of the button append within "content" div
      </p>
      <button id="layoutTextArea" class="btn btn-primary">Click Here</button>
  </div>
</div>

<div class="d-none" id="appendTextArea">
   <h1>
   Test Block
   </h1>
</div>