jQuery / JS:复制类的内容并将其打印在页面上的其他位置

时间:2015-12-23 10:12:46

标签: javascript jquery html

我有一个名为test-parent的课程,如下所示,我想复制两个UL元素的内容,并将内容添加到页面上的其他位置。

   <div class="test-parent">
    <hr>
    <strong>
    <ul style="list-style-type:none">
    <ul style="list-style-type:none">
    </div>

我的jQuery看起来像这样:

(function($) {
    $( document ).ready(function() {
        $( ".options_group").prepend( " <p>Test</p>" );
    });
}(jQuery));

基本上我需要做的就是将类中的两个UL元素添加到options_group类中。有谁知道我怎么做到这一点?感谢

2 个答案:

答案 0 :(得分:1)

试试这个,只需使用each()和clone功能()进行圆顶化。 正如你所说,你需要在其他地方使用ul元素,或者如果你只需要ul中的内容需要相应地修改

(function($) {
    $( document ).ready(function() {
        //$( ".options_group").prepend( " <p>Test</p>" );
        $('.test-parent ul').each(function(){
          $( ".options_group").append($(this).clone());
        });   
    });
}(jQuery));
ul{
   background:red;
   height:100px;
    width:100px;
}

.options_group{

  clear:both;
  border:1px solid black; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


   <div class="test-parent">
    <hr>
     <strong>
     <ul style="list-style-type:none">1</ul>
     <ul style="list-style-type:none">2</ul>
      </strong>

    </div>

 <div class="options_group">
</div>

答案 1 :(得分:0)

您只需使用jQuerys clone function克隆uls:

$(function() {
  $(".copy").prepend($(".test-parent ul").clone());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test-parent">
  <hr/>
  <ul style="list-style-type:none">
    <li>item</li>
  </ul>
    <ul style="list-style-type:none">
    <li>item 2</li>
    </ul>
</div>
<div class="copy">
</div>